gpt4 book ai didi

c - 我的c代码有什么问题?

转载 作者:太空宇宙 更新时间:2023-11-04 06:40:14 25 4
gpt4 key购买 nike

我遇到以下代码的段错误。为了编译,我输入了 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com