2013-04-09 106 views
-5

運行程序錯誤在哪裏? 我知道在這兩個函數的FOR循環中有一個問題。運行程序錯誤 - C

我用調試器運行,我不知道爲什麼會出現錯誤。

該崩潰是: 在program2.exe 0x00E214E5未處理的異常:0xC0000005:訪問衝突寫入位置0x00E25865。

然後程序停止。

我的代碼:

#include <stdio.h> 

char *what1 (char s[], char t[], int n); 
int what2 (char str[], char c); 

int main() 
{ 

    printf("%s\n", what1("hello", "world", 2)); 
    printf("%d\n", what2 ("fkbf", 'o')); 

    return 0; 
} 


char *what1 (char s[], char t[], int n) 
{ 
    char *p=s; 
    while (*s++); 
    for (--s; n-- && (*s=*t); s++, t++); 
    *s='\0'; 
    return p; 
} 

int what2 (char str[], char c) 
{ 
    char *ptr; 
    for (ptr=str; *ptr;) 
     if ((*str=*ptr++)!=c) 
      str++; 
    *str ='\0'; 
    return ptr-str; 
} 
+0

您是否收到錯誤訊息?怎麼了?你期望發生什麼? – EClaesson 2013-04-09 15:42:11

+0

什麼樣的錯誤?它是一個崩潰?或意外的回報?或垃圾打印? ... – MOHAMED 2013-04-09 15:45:49

+0

我不知道修改字符串文字的選擇有哪些問題,但這顯然是一個重複的問題。 – 2013-04-09 15:46:23

回答

3

兩個what1()what2()正在修改的文字傳遞的字符串,這是不確定的行爲,因爲這樣的字符串可以存儲在只讀存儲器。

+0

我認爲該字符串不是隻讀內存。爲什麼字符串是隻讀存儲器,以及如何更改寫入內存? – Michael 2013-04-09 16:10:55