【发布时间】:2013-06-19 14:16:28
【问题描述】:
好的,所以我编写了一个小函数来将字符串中的任何大写字母转换为小写字母,只是为了在我正在学习 C 的书中做一个练习。
除了通过指针将值分配给“字符”之外,一切正常。
这是代码,一切都正确编译,但我收到此运行时错误“未知的伪重定位协议版本 %d”。这就是为什么我尝试打印通过指针更改值的字符。
#include <stdlib.h>
#include <stdio.h>
/*
----------------------------------------------
CONVERTS UPPERCASE CHARACTERS TO LOWERCASE
----------------------------------------------
*/
void lowercase(char * address, char text2){
// used in the for loop
int inc;
// used as an index for text2Copy
int inctwo = 0;
// used in the for loop
int length = strlen(text2);
//used to copy the active character in text2
char text2Copy[length];
for(inc = 0; inc <= length; inc++){
//basicaly if character is a capital leter
if(text2[inc] >= 'A' && text2[inc] <= 'Z'){
//I plus 32 because each letter is 32 numbers away in 'ASCII'
//therefore converting capital to lowercase
text2Copy[inctwo] = text2[inc] + 32;
//add one to help with indexing
inctwo++;
}
//if the character is not a capital leter
else{
text2Copy[inctwo] = text2[inc];
inctwo++;
}
}
//*address = "sdafsdf"; //<-- THIS WORKS!!!
*address = text2Copy;//WHY DOESN"T THIS WORK?
}
int main(){
//just the string I will be using.
char * text = "'CONVERT capitals TO lower CASE'";
//print the string to show the original
printf("%s\n",text);
lowercase(&text,text);
//This is where I want the value from the function to print out
printf("%s\n",text);
return 0;
}
如果您能帮助我,我将不胜感激,我真的很困惑,并且对为什么这不起作用有点恼火。如果您需要我更好地解释它,请提出要求,我希望我已经做得足够了。
谢谢,杰克。
/////////////////////////////////////// ///////编辑////////////////////////////////////////// ////////////////
好的,我已经使用了您的所有建议,谢谢:D
现在它除了一个我不知道如何修复的奇怪错误之外目前还可以工作。
第一个字符以外的所有字符都变成小写字符。
现在发生了什么->“+将大写转换为小写”我不知道为什么第一个字符会这样做?有什么想法吗?
这是新代码。
#include <stdlib.h>
#include <stdio.h>
/*
----------------------------------------------
CONVERTS UPPERCASE CHARACTERS TO LOWERCASE
----------------------------------------------
*/
void lowercase(char * address, char text2[]){
// used in the for loop
int inc;
// used in the for loop
int length = strlen(text2);
for(inc = 0; inc <= length; inc++){
//basicaly if character is a capital leter
if(text2[inc] >= 'A' && text2[inc] <= 'Z'){
//I plus 32 because each letter is 32 numbers away in 'ASCII'
//therefore converting capital to lowercase
text2[inc] += 32;
//add one to help with indexing
inctwo++;
}
//if the character is not a capital leter
else{
inctwo++;
}
}
*address = text2;
}
int main(){
//just the string I will be using.
char text[] = "cONVERT capitals TO lower CASE";
//print the string to show the original
printf("%s\n",text);
lowercase(&text,text);
//This is where I want the value from the function to print out
printf("%s\n",text);
return 0;
}
【问题讨论】:
-
您正在尝试修改字符串文字,这是未定义的行为,并且通常会导致段错误,因为字符串文字(通常)存储在只读内存中。是重复的,让我搜索一下。
-
啊,好的,谢谢:D 有没有办法可以将它放入读/写内存中?
-
我认为你可以在运行时创建动态字符串
char text2Copy[length];。将此更改为char text2Copy[20];只是为了测试,看看你得到了什么? -
而修复是
char text[] = "'CONVERT capitals TO lower CASE'";使其成为一个数组,这样你就可以修改内容了。