C 将指向的字符替换为其他字符
更具体地说,我试图用四个星号替换指针指向的四个字符的单词,而不使用字符数组。 因此,如果我有char*word=word这个词,使用这个方法会返回**** 这是我到目前为止得到的C 将指向的字符替换为其他字符,c,C,更具体地说,我试图用四个星号替换指针指向的四个字符的单词,而不使用字符数组。 因此,如果我有char*word=word这个词,使用这个方法会返回**** 这是我到目前为止得到的 void four_stars(char *start){ char *temp = start; int length = 0; while(*temp){ length++; temp++; } if(length==4){ w
void four_stars(char *start){
char *temp = start;
int length = 0;
while(*temp){
length++;
temp++;
}
if(length==4){
while(length>=0){
start = '*';
start++;
length--;
}
}
}
我用单词char*word=This对它进行了测试,结果就是这个单词。
我对c编程非常陌生,那么我做错了什么呢?如果您有char*word=word,那么就不可能修改word。这是因为,在C和C++中,字符串文字不能修改。必须从可写内存区域中的字符串开始,例如:
// the code you wrote has a few flaws
// rather than trying to list the flaws
// I just provide a simplistic/brute force example to accomplish the function
void four_stars(char *start)
{
start[0] = '*';
start[1] = '*';
start[2] = '*';
start[3] = '*';
}
char word[] = "Word";
或
如果您更改start='*',那么您的函数将工作;到*开始='*' whilelength>=0{start='*';->whilelength>0{*start='*';在调用方字符[]=this而不是start='*';start++;您应该执行*start++='*',以及@BLUEPIXY loop test>0。技术要点:您的代码也将ab!视为四个字母的单词。是否有实际原因无法使用strlen获取长度?@Leon无法更改字符串文字。它是UB。这是seg-fault的原因。它忽略了所需的起始长度为4。^我只想替换长度为4且只有4的单词。但我可以更改指针指向的单个字符,对吗?@Leon是的,只要这些字符是可修改的。您不能更改不可修改的内容。
char *word = malloc(5);
strcpy(word, "Word");