waruni guna waruni guna - 2 months ago 19
C Question

assignment from incompatible pointer type [-Wincompatible-pointer-types]

I'm new to c programming. I'm learning pointers in c, i tested simple file operation. In order to overcome overwrite the values in txt file. I declare file globally and inside the method i initialize the local pointer address to global pointer address. my intention is use the same memory location. By using the same memory location carry out the file operations . Please be kind enough to find my program below.

FILE *f;// global pointer.

void myTest(char* val) {
//d is local pointer.
FILE *d = fopen("file.txt", "w");
f=&d;
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
// print the data
fprintf(f, "%s\n",val);

}

int main(void) {

myTest("test");
fclose(f);
}


warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
f=&d;
After i run the bin file i get the
Segmentation fault (core dumped) Error.

Answer

d is a FILE *, so &d is a FILE **. That can't be assigned to f which is a FILE *.

What you want is f=d. Or just get rid of d entirely:

f = fopen("file.txt", "w");