我是新手学习C语言。下面代码中的字符串赋值可行:
#include<stdio.h>
int main(void){
char str[] = "string";
printf("%s\n",str);
}
但是在下面的情况下不起作用,即使我给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;
}
为什么会发生这种情况?
char name[10];
,你会得到一个有十个元素的数组,编号从0到9(包括)。所以a.name[10]
超出了数组的范围。尝试为它赋值不是一个好主意。 - David Schwartz