I’m new to C. The string assignment in the following code works:
#include<stdio.h>
int main(void){
char str[] = "string";
printf("%s\n",str);
}
But doesn’t work in the following,even I give the index number to the name[]:
#include <stdio.h>
int main(void){
struct student {
char name[10];
int salary;
};
struct student a;
a.name[10] = "Markson";
a.salary = 100;
printf("the name is %s\n",a.name);
return 0;
}
Why does this happen?
You can’t assign to an array. Two solutions: either copy the string:
or use a const char pointer instead of an array and then you can simply assign it:
Or use a non-const char pointer if you wish to modify the contents of “name” later:
(Don’t forget to free the memory allocated by strdup() in this latter case!)