使指针指向c中的字符数组

making a pointer point to an array of characters in c

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct node
{
    char *arr;
    struct node *next;
} node;

int main()
{
    char *word = (char *)malloc(sizeof(char) * 20);
    strcpy(word, "jon jones");

    node *sentence;
    sentence->arr = word;         //Problem here
    printf("%s", sentence->arr);

    return 0;
}

我正在尝试动态分配一个字符数组。将一个字符串放在那里,然后使节点的数据元素指向字符数组。当我 运行 程序出现分段错误时。我怀疑它来自我上面标记的行。我不明白的是,我让 sentence->arr 指向单词数组的第一个元素。为什么会这么崩溃?提前致谢。

node *sentence;
sentence->arr = word;         //Problem here

指针 sentence 已声明,但未初始化和取消引用,因此会导致未定义的行为。

在取消引用之前分配内存 -

node *sentence;
sentence=malloc(sizeof(*sentence));

此外,如果你想制作节点,请使用 strcpy 而不是这个 -

sentence->arr = word;       // but allocate memory to `arr` before copying

你忘了初始化你的句子变量。

以下适合我

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct node
{
    char *arr;
    struct node *next;
}node;

int main()
{
    char *word = (char *)malloc(sizeof(char) * 20);
    strcpy(word, "jon jones");

    node *sentence = (node*)malloc(sizeof(node)); // Initialize node area
    sentence->arr = word; 
    printf("%s", sentence->arr);

    return 0;
}

您正在使用指向节点的指针,但该节点尚未分配。 采用 : node sentence; sentence.arr = word; printf("%s", sentence.arr);

应该会更好。 您还可以使用 gdb 找出导致错误的线路。

要么像为 word 一样为 node 分配内存,要么使用结构而不是结构指针。

node *sentence;
sentence = (node*)malloc(sizeof(node));
sentence->arr = word;         
printf("%s", sentence->arr);

node sentence;
sentence.arr = word;         
printf("%s", sentence->arr);