我遇到以下代码的段错误。为了编译,我输入了 gcc -std=c99 -g alphacode.c
。这是我从 here 解决的问题,我不确定是什么问题。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int catchar(char a, char b) {
char a1[2];
a1[1] = a;
a1[0] = b;
return atoi(a1);
}
int processNumber(char *num) {
int size = strlen(num);
int p[size];
if (num[size-1] != 0)
p[size-1] = 1;
else
p[size-1] = 0;
int i;
for (i = size-2; i>=0; i--)
{
if (catchar(num[i], num[i-1]) > 26 ||
catchar(num[i] , num[i-1]) <1 || num[i] == 0)
p[i] = p[i-1];
else
p[i] = p[i-1] + p[i-2];
}
return p[0];
}
int main() {
int bytes_read;
int nbytes = 5000;
char *number;
bytes_read = getline (&number, &nbytes, stdin);
while (bytes_read != -1) {
int out = processNumber(number);
printf("%d\n", out);
bytes_read = getline (&number, &nbytes, stdin);
}
return 0;
}
最佳答案
int catchar(char a, char b) {
char a1[2];
a1[1] = a;
a1[0] = b;
return atoi(a1);
}
atoi()
需要一个字符串,并且字符串必须有一个 '\0'
终止符,没有它 - atoi()
将继续寻找,直到找到 '\0'
,如果分配的内存不足,您可能会遇到垃圾或段错误。
您应该声明大小为 3 的数组,并将 '\0'
放在索引 2 处。
关于c - 我的c代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9582049/