谁能告诉我如何解决分段错误?我仍然处于课程的早期阶段。我知道分段错误与我的数组和变量“storedplain”有关。我的意图是创建一个 int 类型的数组,然后在接下来的步骤中将用户键入的所有 char 变量存储为我的代码的 int。
string plaintext = get_string(" plaintext: ");
int storedplain[] = {0};
for(int i = 0; i < strlen(plaintext); i++)
{
char conversion2 = plaintext[i];
storedplain[i] = conversion2;
}
int storedplain[] = {0};
是一样的int storedplain[1] = {0};
。
这意味着storedplain[i] = conversion2
将写入超过的结尾,storedplain
因为i < strlen(plaintext)
将导致i
大于 0 的值。
一个解决方案将是类似的东西int storedplain[MAX_STRING] = {0};
。这只有在您知道可以返回的最大字符串大小时才有效。
最好的解决方案是使用malloc()
:
int * storedplain = malloc(strlen(plaintext) * sizeof(int));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句