有关c++函数内外给变量赋值的差别
c语言吧
全部回复
仅看楼主
level 1
虎59高手 楼主
这是一个测试的代码:
#include<stdio.h>
char *str1[1][1];
char *str2="str 2";
int main() {
str1[0][0]="str 1";
printf("%s\n%s",str1[0][0],str2);
}
输出也很合理:
然后把他改一下:
#include<stdio.h>
char *str1[1][1];
str1[0][0]="str 1";//把这个赋值放到了主函数外
char *str2="str 2";
int main() {
printf("%s\n%s",str1[0][0],str2);
}
事情就出现了:
报错信息:
方便复制报错信息:
[Error] 'str1' does not name a type
[Warning] deprecated conversion from string constant to 'char*' [-Wwrite-strings]
差别只有数组中变量赋值在函数里面还是外面
但是很明显不在数组里的变量在函数外面赋值完全没有问题
我无法理解,有人知道原因吗
(dev c++ 编译)
2021年11月18日 09点11分 1
level 12
初始化和赋值不一样。
2021年11月18日 14点11分 3
level 12
你只能在函数外定义变量,不能赋值,它认为这是定义,但是缺少类型了。
2021年11月18日 14点11分 4
level 7
你在函数外只能定义,或者声明变量,不能赋值变量
你的char *s2语句本质上也是定义而不是赋值,
C语言语法规定如此,
2021年11月18日 16点11分 5
level 4
全局变量要么直接声明,要么声明的同时初始化。
2021年11月18日 16点11分 7
1