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.
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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.