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

标签 c

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

相关文章:

c - 我有一个 csv 文件,我想将数据放入结构中,但我不知道为什么它只保留最后一行

并发:使用 pthread_mutex 原子化增量操作

c - 期待;在字符串声明的末尾

c - 二进制搜索树插入抛出段错误

C 套接字 - 接收 : connection reset by peer

c - 在销毁它之前确保没有线程在等待临界区

c - 基于字符串比较的单词翻译程序——堆内存断言失败

c - `something_t* x = malloc(sizeof(*x))` 有什么问题吗?

c - 'C' 显示为 2 个不同的值?

c - 使用通配符 ip 的套接字绑定(bind)