Reputation: 207
struct list{
char *Name;
};
void chekFC(struct list *newList){
char *fC = newList->Name;
printf("%s\n", &fC); //I can print it
if(fC[0] == '+') //Any error??
printf("Yes");
}
int main(){
struct list *newList = (struct list *)malloc(sizeof(struct list));
newList->Name = "+abc";
chekFC(newList);
}
it can run, if I change the code to following
void chekFC(struct list *newList){
char *fC = newList->Name;
printf("%s\n", &fC); //I can print it
if(fC[0] == '+') {} // Add {} nothing run in the if condition, than the program can run
printf("Yes");
}
Why this program cannot run? The error is Segmentation fault (core dumped)
Upvotes: 0
Views: 570
Reputation: 646
there have one problem in you code.
printf("%s\n", &fC);
you should change it to
printf("%s\n", fC);
I think you don't understand the C pointer very clearly. the &fC is very different from fC, you can print it by "%p" to see it.
printf("fC %p, &fC %p\n", fC, &fC);
&fC is address of fC, fC is address of string of "+abc". I want it can help you, but I suggest you should read some book, to learn C pointer.
Upvotes: 1
Reputation: 78903
printf("%s\n", &fC);
is wrong, you probably mean
printf("%s\n", fC);
Upvotes: 0
Reputation: 11547
To consistently avoid such problems in the future, I recommend using assertions:
assert(newList);
assert(newList->Name);
Upvotes: 1