我正在寫一個代碼,用word-Y代替word-X。C指針和內存 - 寫了一個代碼...拋出異常
- 正文中的每個單詞長度相同。
- 讓說我的字符串,X,Y分別是:
「AAA BBB CCC DDD QQQ」,X = 2,Y = 5
所以它會打印:「AAA QQQ CCC ddd bbb「
但由於某些原因,我不理解它會拋出異常。 我在代碼中寫了錯誤。 我知道我的代碼有點混亂,所以如果你也有建議,我很樂意聽到。
謝謝!!!
void changeWords(char *s,int X, int Y)
{
int len,words,i,count;
len = count = words = i = 0;
bool flag = false;
while (s[len] != ' ')
len++;
char *p1 = (char*)malloc(sizeof(char)*(len+1));
if (p1== NULL)
{
printf("Error: memory did not allocated");
exit(1);
}
char *p2 = (char*)malloc(sizeof(char)*(len+1));
if (p2== NULL)
{
printf("Error: memory did not allocated");
exit(1);
}
while (flag == false)
{
if (count == (X-1))
{
for(int x = 0; x< len;x++,i++)
p1[x] = s[i];
}
else if (count == (Y-1))
{
for (int x = 0; x< len; x++,i++)
p2[x] = s[i];
flag = true;
}
if (s[i] == ' ')
count++;
i++;
}
p1[len] = p2[len] = '\0';
i = count = 0;
flag = false;
while (flag == false)
{
if (count == (X-1))
{
for (int x = 0; x< len; x++, i++)
s[i] = p1[x]; // here it throw an error "Unhandled exception thrown:.."
}
else if (count == (Y-1))
{
for (int x = 0; x< len; x++, i++)
s[i] = p2[x];
flag = true;
}
if (s[i] == ' ')
count++;
i++;
}
puts(s);
free(p1); free(p2);
}
void main()
{
char*str = (char*)malloc(sizeof(char));
if (str == NULL)
{
printf("Error: memory did not allocated");
exit(1);
}
char ch;
int i = 0;
printf("Enter a string: ");
while ((ch = getchar()) != '\n')
{
str[i] = ch;
i++;
str = realloc(str, sizeof(char) * (i + 1));
if (str == NULL)
{
printf("Error: memory did not allocated");
exit(1);
}
}
str[i] = '\0';
func(str,3,5);
printf("new string: %s\n", str);
free(str);
system("pause");
}
}
你是否在調試器中檢查了代碼並檢查了標記的行上的值? – xxbbcc
字符串文字不能更改。 – BLUEPIXY
's'是一個字符串文字,並且正在'changeWords'中修改它,這是未定義的行爲。改爲'char str [] =「aaa bbb ccc ddd qqq」;'(但不保證這是唯一的問題) – yano