2014-02-26 24 views
1

我有一段代碼在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)時發出運行時錯誤。我的問題是什麼?

+0

str2是隻讀的 –

回答

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 
2

char* str2 = "goodbye matey"相當於宣佈static const char str2[] = "goodbye matey"。所以你不能修改str2指向的內容。

相關問題