Eric Tang
Eric Tang

Reputation: 207

c char pointer compare

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

Answers (5)

laifjei
laifjei

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

Jens Gustedt
Jens Gustedt

Reputation: 78903

printf("%s\n", &fC);

is wrong, you probably mean

printf("%s\n", fC);

Upvotes: 0

user1202136
user1202136

Reputation: 11547

To consistently avoid such problems in the future, I recommend using assertions:

assert(newList);
assert(newList->Name);

Upvotes: 1

dexametason
dexametason

Reputation: 1133

newList->name has never been allocated.

Upvotes: 1

Andreas Brinck
Andreas Brinck

Reputation: 52519

Are you sure newList->Name has been allocated?

Upvotes: 1

Related Questions