我有一段代碼在char[]
上正常工作,但在char*
上執行時會產生運行時錯誤。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)
時發出運行時錯誤。我的問題是什麼?
str2是隻讀的 –