我正在写一个代码,用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