if use it without "static" - will get delirious values instead of a1
#include <stdio.h>
int* MyFunction(int a, int b, int c)
{ static int array[3];
array[0] = a;
array[1] = b;
array[2] = c;
return array; } // return a pointer.
int* func2(int a, int b )
{ static int array[3];
array[0] = 0;
array[1] = 0;
return array; } // return a pointer.
int main (void)
{ int *a1, *a2; // int pointers
printf("calling a1 = MyFunction(10,20,30);\t");
a1 = MyFunction(10,20,30);
printf("a1 has %d %d %d\n",a1[0],a1[1],a1[2]);
printf("calling a2 = MyFunction(100,200,300);\t");
a2 = MyFunction(100,200,300);
printf("a2 has %d %d %d\n",a2[0],a2[1],a2[2]);
printf("\nLooks good, except...\t");
printf("a1 now has %d %d %d\n",a1[0],a1[1],a1[2]);
printf("calling a2 = MyFunction(10,200,300);\t");
a2 = MyFunction(10,200,300);
printf("a1 has %d %d %d\n",a1[0],a1[1],a1[2]);
// getchar();
return 0;
}
in this connection - pair of questions:
1) does this mean that i can't for example pass in function file pointer FILE* (only one parameter) and return char** - array of strings which definition and memory allocation take place in body of my function (for multiple times universal using - without rewriting of returning parameter memory)?
2) why in this case I got "good" array in first printf() (after exit from MyFunction() ) but don't in second printing a1 by printf (also after exit from MyFunction()):
#include <stdio.h>
int* MyFunction(int a, int b, int c)
{ int array[3];
array[0] = a;
array[1] = b;
array[2] = c;
return array; } // return a pointer.
int main (void)
{ int *a1, *a2; // int pointers
printf("calling a1 = MyFunction(10,20,30);\t");
a1 = MyFunction(10,20,30); // works and exits from "local" memory scope
printf("a1 has %d %d %d\n",a1[0],a1[1],a1[2]);// first
printf("\nLooks good, except...\t");
printf("a1 now has %d %d %d\n",a1[0],a1[1],a1[2]); // second
// getchar();
return 0;
}
as I understand - C shouldn't give adequate array values outside of MyFunction (if we don't use static) . What is wrong in my
reasoning?