簡體   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