【发布时间】:2020-06-11 19:35:21
【问题描述】:
我不断收到分段错误错误,我似乎找不到问题所在。
一个例子是:
输入:4 bbbb
输出:2 abab
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
int a, len, i = 0, count = 0;
scanf("%d", &a);
len = a;
char *strn = malloc((len * sizeof(char*)) + 1);
scanf("%s", strn);
while (i != len) {
if (strn[i]=='a' && strn[i+1]=='a') {
strn[i] = 'b';
count++;
i++;
} else if (strn[i]=='b' && strn[i+1]=='b') {
strn[i] = 'a';
count++;
i++;
} else {
i+=2;
}
}
printf("%d\n%s\n", count, strn);
free(strn);
return 0;
}
【问题讨论】:
-
??????小心前行,看看会发生什么?
-
您的意思可能是
sizeof(char)或基本上是1,而不是sizeof(char*),它是系统上指针的大小。 -
我认为您需要
while (i < len-1),因为i可能会比len更大而永远不会相等,并且您正在访问i之外的一个。 -
输入字符串后应设置
len = strlen(strn);。 -
弗雷德,谢谢!我的错误与 while 循环条件有关。
标签: c memory-leaks segmentation-fault