Reputation: 49
I'm new to C language and I'm very curious about the best way to declare string in c.
Example:
char *name;
//or char name[];
scanf("%s", &name);
printf("Hello %s !", name);
Which of these two will be better in this case?
char *name;
char name[];
Upvotes: 0
Views: 110
Reputation: 1132
char *name;
is a pointer which points the address of the of the first index of your string. This is mostly use if your manipulating the variable by reference eg(passing parameter by reference)
char name[]
is not applicable in C since you must initialise your array size e.g. char name[20];
Either way, the latter with the correct syntax is better.
Upvotes: 0
Reputation: 126
If you have a string with constant length. You can declare an array of char like this.
char name[64];
scanf("%s", name); // no more than 63 characters, remember the '\0'
printf("Hello %s\n", name);
If the string length is dynamic, please use the function malloc to allocate a specific length of memory. What's more you should remember to free the memory allocated before.
Upvotes: 1