不同的字符串初始化会产生不同的行为? [英] Different string initialization yields different behavior?
问题描述
为什么当我使用下面的方法,将用于所有字符转换成字符串为大写,
而(*后code){
*后code = TOUPPER(*后code);后code ++;
}
使用以下几种说法作品,
字符错误[20];
的strcpy(错了,LA1 4yt);
但下面没有,尽管他们是一样的吗?
的char *错=LA1 4yt
在尝试我的程序崩溃写入非法地址(段错误,我presume)。它是与不是的malloc
荷兰国际集团的问题吗?没有空terimanted?它不应该是...
经过调试,我注意到它崩溃上的第一个字符指定为大写的尝试。
任何帮助AP preciated!
的char *错=LA1 4yt
该声明指向一个字符串常量。常量不能被修改,这就是为什么你的code崩溃。如果你写的更多的迂腐
为const char *错=LA1 4yt //更好
那么编译器会赶上的错误。你或许应该这样做声明指向一个字符串,而不是创建一个数组的任何时间。
有二十个字符,以便写入空间此,在另一方面,器分配的读/写存储是细
字符错误[20];
如果你想把它初始化字符串上面,你可以这样做,然后将被允许去改变它。
字符错误[20] =LA1 4yt //可以修改
char的错误[] =LA1 4yt //可以修改;仅大到需要
How come when I use the following method, to be used to convert all the characters in a string to uppercase,
while (*postcode) {
*postcode = toupper(*postcode);
postcode++;
}
Using the following argument works,
char wrong[20];
strcpy(wrong, "la1 4yt");
But the following, doesn't, despite them being the same?
char* wrong = "la1 4yt";
My program crashes in an attempt to write to an illegal address (a segfault, I presume). Is it an issue with not malloc
ing? Not being null-terimanted? It shouldn't be...
Through debugging I notice it crashes on the attempt to assign the first character as its uppercase.
Any help appreciated!
char* wrong = "la1 4yt";
This declares a pointer to a string constant. The constant cannot be modified, which is why your code crashes. If you wrote the more pedantic
const char* wrong = "la1 4yt"; // Better
then the compiler would catch the mistake. You should probably do this any time you declare a pointer to a string literal rather than creating an array.
This, on the other hand, allocates read/write storage for twenty characters so writing to the space is fine.
char wrong[20];
If you wanted to initialize it to the string above you could do so and then would be allowed to change it.
char wrong[20] = "la1 4yt"; // Can be modified
char wrong[] = "la1 4yt"; // Can be modified; only as large as required
这篇关于不同的字符串初始化会产生不同的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!