2012-09-11 40 views
0

可能重複:
Why do I get a segmentation fault when writing to a string?
What is the difference between char a[] = 「string」; and char *p = 「string」;未處理的異常與cstrings工作

我已經找到了故障,但我不知道爲什麼。你會幫助我嗎?

如果我定義了char str[],而不是在主函數的char * str,它可以正常工作,否則的*pSlow = *pFast;線將與"Unhandled exception at 0xf3 in shanchu.exe: 0xC0000005: Access violation writing location 0xc."

感謝

崩潰
#include <stdio.h>  
#include <string.h>  
#include <iostream> 

char * delChar(char *s,int iLen)  
{  
    if((s == NULL) || iLen <= 0)  
    {  
     return NULL;  
    }  
    int i;  

    const int MAXLEN = 26;  

    unsigned int min,hashTable[MAXLEN];  

    for(i = 0;i < MAXLEN;i ++)  
    {  
     hashTable[i] = 0;  
    }  

    for(i = 0;i < iLen;i ++)  
    {  
     hashTable[*(s + i) - 'a'] ++;  
    }  

    while(hashTable[i] == 0)  
    {  
     i ++;  
    }  
    min = hashTable[i];  

    for(i = 0;i < MAXLEN;i ++)  
    {  
     if(hashTable[i] != 0)  
     {  
      if(hashTable[i] < min)  
      {  
       min = hashTable[i];  
      }  
     }    
    }  

    char *pSlow = s; 
    char *pFast = s;  
    while(*pFast != '\0')  
    {  
     if(hashTable[*pFast - 'a'] != min)  
     {  
      *pSlow = *pFast;  
      pSlow ++; 
     }   
     pFast ++; 
    }  
    *pSlow = '\0'; 

    return s;  
}  
int main()  
{  
    char* str = "abadccdehigiktk";  
    int iLen = strlen(str)/sizeof(char);  
    char *tmp = delChar(str,iLen);  
    printf("%s\n",tmp); 
system("pause"); 

}  
+0

考慮使用std :: string代替 – nogard

回答

4
char* str = "abadccdehigiktk"; 

string-literal不應該改性。在您的功能delChar中,您正在嘗試修改string-literal。這是未定義的行爲。

您應該使用

char[] str = "abadccdehigiktk"; 

或MB std::string(因爲你寫C++)。

+0

是的,太好了。非常感謝你! – crazyer

0

這部分是完全錯誤的:

while(hashTable[i] == 0)  
{  
    i ++;  
}  
min = hashTable[i];  

for(i = 0;i < MAXLEN;i ++)  
{  
    if(hashTable[i] != 0)  
    {  
     if(hashTable[i] < min)  
     {  
      min = hashTable[i];  
     }  
    }    
}  

首先i尚未初始化所以這將是離開這裏的範圍(它最初將等於「艾朗」以前的「for」循環的原因) 。其次,邏輯是一團糟,你可以在一個循環中做到這一點。我想你可能是想在這裏做的是:

min = UINT_MAX; 
for (i = 0; i < MAXLEN; i++)  
{ 
    if (hashTable[i] > 0 && hashTable[i] < min) 
    { 
     min = hashTable[i]; 
    } 
} 

即找到在哈希表中的最小非零值。

+0

是的,我應該初始化爲0,我的邏輯是一團糟。感謝您的方法。這十分完美。謝謝 。但是我的錯不在這裏,謝謝你的回答,並且幫助我優化我的程序。 – crazyer

1

此行

char* str = "abadccdehigiktk"; 

限定一個指向恆定字符串,即字符串可以不進行修改。如果你將它聲明爲一個數組(char str[])它是一個數組在棧上,因此可以修改。

至於刪除字符,爲什麼不使用例如而不是memmove

// "Delete" the fourth character of a string 
memmove(str + 3, str + 4, strlen(str) - 3); 

如果使用std::string相反,它是突然容易使用std::string::erase

std::string str = "abadccdehigiktk"; 

// Remove the fourth character 
str.erase(3, 1); 

您也不必擔心指針數組相比。

+0

你幫我了,謝謝。但如果我已經定義了像「char * str =」abadccdehigiktk「;」我想刪除第4個字符,我應該怎麼做?謝謝。 – crazyer

+0

@crazyer你簡直不能像使用指針時的字符串是_constant_。你必須使用一個數組。 –

+0

我明白了,謝謝。 – crazyer