c - c 中包含字符串的链接列表

标签 c linked-list

struct node
{
    char *IPArray[100];
    struct node *ptr;
};
typedef struct node NODE;

NODE *head, *first, *temp = 0;

first = 0;

int numofIP;

这是我的结构,在链表中的每个节点都包含字符串。 numofIP 是我的链表中字符串或节点的最大数量。

for(int i=0; i<numofIP; i++)
{
    head  = (NODE *)malloc(sizeof(NODE));
    printf("enter the IP addresses:\n");
    scanf("%s",&head->IPArray[i]);

    if(first != 0)
    {
        temp->ptr = head;
        temp = head;
    }
    else
    {
        first = temp = head;
    }
}

temp->ptr = 0;
temp  = first;

这就是我接受输入并将其存储在每个节点中的方式。

while(temp != NULL)
{
    printf("%d=> ",temp->IPArray);
    temp = temp->ptr;
}

这就是我打印链接列表的方式。

但问题是我在输出中得到了地址。我无法弄清楚。如何在链表的每个节点中存储一个字符串?

最佳答案

1.更改

printf("%d=> ",temp->IPArray);

printf("%s=> ",temp->IPArray);

您为 printf 函数提供了不正确的格式说明符。

2.为IPArray中的每个char*分配内存。

但是,正如您所提到的,节点中只需要一个字符串,然后更改 char* IPArray[100]char IPArray[100]

char* IPArray[100] :将创建指向 100 个字符串的指针,稍后您需要为其分配内存。

char IPArray[100] :将创建 100 个字符的数组,您可以在其中存储特定节点的 IP 地址,并且不需要为此分配单独的内存。

关于c - c 中包含字符串的链接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35788734/

相关文章:

c - Shell_NotifyIcon() 和一个不可见的窗口

c - 如何将新项目插入到C中的链接列表中(在列表末尾)

java - 如何删除链表中的特定节点

python - 简单的链表队列

c - 在 openSSL 中手动设置 AES key ?

c - sscanf 从头开始​​读取

c - 如何在没有终端的情况下启动 gvim?

c - Malloc 不会创建具有所需大小的结构数组

python - 了解如何在链表中找到中间节点的 while 循环条件

c - 这是最佳的转变方式吗?