繁体   English   中英

链表中的双指针

[英]Double pointers in a linked list

我正在尝试将字符串存储在链表中,但由于某种原因,我不断收到分段错误错误。 我已经尝试了一切,我觉得我错过了一些非常愚蠢和简单的东西,请有什么想法吗?

    #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 60
typedef struct Node
{
    char *getInput;
    struct Node *next;

} Node;
typedef struct list
{
    Node *head;
} list;

void readText(Node **a)
{
    
  char c;
    int i = 0;
     while ((c = getchar()) != EOF)
        (*a)->getInput[i++] = c;
}
void main()
{
    Node *b;
  
    b->getInput = (char *)calloc(SIZE, sizeof(char));
    if (b == NULL)
    {
        printf("sadsa");
        exit(1);
    }
   readText(&b);
    printf("%s", b->getInput);
}
  • 在取消引用之前,您必须分配一个有效区域并分配给b
  • 在取消引用之前,还必须检查b是否不是NULL
  • 您应该在托管环境中使用标准int main(void)而不是void main() ,这在 C89 中是非法的,并且在 C99 或更高版本中是实现定义的,除非您有特殊原因使用非标准签名。
  • getchar()返回int ,因此应将返回值分配给int变量。 否则,将很难区分有效字符和 EOF。
  • 您应该在使用%s之前通过添加终止空字符来终止字符串。 (在这种情况下没有必要,因为缓冲区已通过calloc()初始化为零,但这将提高该函数的其他用途的安全性)
void readText(Node **a)
{
    
    int c; /* use proper type */
    int i = 0;
    while ((c = getchar()) != EOF)
        (*a)->getInput[i++] = c;
    (*a)->getInput[i] = '\0'; /* terminate the string */
}

int main(void) /* use standard signature */
{
    Node *b = malloc(sizeof(*b)); /* allocate buffer */
    if (b == NULL) /* check if allocation is successful before dereferencing */
    {
        printf("sadsa");
        exit(1);
    }
    b->getInput = (char *)calloc(SIZE, sizeof(char));
    readText(&b);
    printf("%s", b->getInput);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM