我有一段代码可以在char[]
上正常运行,但在char*
上执行时会出现运行时错误。
#include <stdio.h>
#include <string.h>
void rotateLeft(char* str, int pos, int size){
char temp;
int i;
for(i=pos; i < size-1; i++) {
temp = str[i];
str[i] = str[i+1];
}
str[size-1] = temp;
}
void removeAllDups(char* str) {
int size = strlen(str);
int i,j;
char cur;
for (i=0; i<size; i++) {
cur = str[i];
for(j=i+1; j<size;) {
if (str[j] == cur) {
rotateLeft(str, j, size);
size--;
str[size] = '\0';
}
else {
j++;
}
}
}
}
int main(void) {
char str1[] = "hello there";
char* str2 = malloc(sizeof(char)*14);
strcpy (str2, "goodbye matey");
removeAllDups(str1); // succeeds
printf("%s\n", str1);
removeAllDups(str2); // fails
printf("%s\n", str2);
free(str2);
return 0;
}
达到removeAllDups(str2)
时会出现运行时错误。我的问题是什么?
答案 0 :(得分:2)
char* str2 = "goodbye matey"
相当于声明static const char str2[] = "goodbye matey"
。因此,您无法修改str2
指向的内容。
答案 1 :(得分:2)
char* str2 = "goodbye matey";
使用指向不应更改的数据的指针初始化str2
。虽然str2
指向此类数据,但通过修改会导致UB。
char str1[] = "hello there";
char* str2 = "goodbye matey";
removeAllDups(str2); // fails
str2 = str1;
removeAllDups(str2); // OK
str2 = "goodbye matey2";
removeAllDups(str2); // fails
str2 = strdup("goodbye matey3");
removeAllDups(str2); // OK