C printf(“%s”)返回奇怪的值
我有一个函数,它可以处理字符串,但是它必须保存原始字符串,将其复制到一个字符数组中,使其全部大写,并用任何w/w替换VC printf(“%s”)返回奇怪的值,c,C,我有一个函数,它可以处理字符串,但是它必须保存原始字符串,将其复制到一个字符数组中,使其全部大写,并用任何w/w替换V char* function(const char* text){ int textLength = strlen(text); char text_copy[textLength]; for(int i = 0; i < textLength; i++){ if(text[i] == 'W' || text[i] == 'w') te
char* function(const char* text){
int textLength = strlen(text);
char text_copy[textLength];
for(int i = 0; i < textLength; i++){
if(text[i] == 'W' || text[i] == 'w')
text_copy[i] = 'V';
else
text_copy[i] = toupper(text[i]);
}
return 'a';
}
为什么有些弦乐演奏得很好,而有些弦乐演奏得不好?谢谢
为什么有些弦乐演奏得很好,而有些弦乐演奏得不好
纯属偶然
只能为字符串中的可见字符分配足够的空间,而不能为终止的\0
分配足够的空间。幸运的是,对于某些字符串,空字节正好位于字符数组之后的堆栈上
像这样更改代码
int textLength = strlen(text);
char text_copy[textLength + 1]; // << enough space for the strings and \0
for(int i = 0; i < textLength; i++){
if(text[i] == 'W' || text[i] == 'w')
text_copy[i] = 'V';
else
text_copy[i] = toupper(text[i]);
}
text_copy[textLength] = '\0'; // Make sure it is terminated properly.
int textLength=strlen(文本);
char text_copy[textLength+1];//
为什么有些弦乐演奏得很好,而有些弦乐演奏得不好
纯属偶然
只能为字符串中的可见字符分配足够的空间,而不能为终止的\0
分配足够的空间。幸运的是,对于某些字符串,空字节正好位于字符数组之后的堆栈上
像这样更改代码
int textLength = strlen(text);
char text_copy[textLength + 1]; // << enough space for the strings and \0
for(int i = 0; i < textLength; i++){
if(text[i] == 'W' || text[i] == 'w')
text_copy[i] = 'V';
else
text_copy[i] = toupper(text[i]);
}
text_copy[textLength] = '\0'; // Make sure it is terminated properly.
int textLength=strlen(文本);
char text_copy[textLength+1];// 您需要使用null终止副本
char text_copy[textLength+1];
...
text_copy[textLength]='\0';
但是,如果您是从函数返回它(这还不清楚),您应该将其替换为mallock。您需要null终止副本
char text_copy[textLength+1];
...
text_copy[textLength]='\0';
虽然如果您是从函数返回它(这还不清楚),您应该将其替换为mallocing。text\u copy
具有局部作用域,并且它不是以空结尾的
,也没有空终止符的空间。。。。。问号是否出现在输出中,还是用于标记以非预期方式处理的字符串?@LPs将text\u copy
设置为textLength+1
,然后设置text\u copy[textLength]='\0'代码>似乎已经解决了这个问题。谢谢它实际上取决于您在哪里使用printf
text\u copy
具有本地作用域,并且它不是空终止的
,也没有空终止符的空间。。。。。问号是否出现在输出中,还是用于标记以非预期方式处理的字符串?@LPs将text\u copy
设置为textLength+1
,然后设置text\u copy[textLength]='\0'代码>似乎已经解决了这个问题。谢谢这取决于您在哪里使用printf
工作,谢谢。它不应该从函数中返回,但是感谢您的提醒!很好,谢谢。它不应该从函数中返回,但是感谢您的提醒!