gpt4 book ai didi

c - 在 C 中使用函数填充的指向结构的指针数组

转载 作者:太空宇宙 更新时间:2023-11-04 02:33:31 33 4
gpt4 key购买 nike

我正在尝试编写一个程序来填充指向结构的指针数组,但使用一个函数来执行此操作。我相信我对指针做错了什么,因为我需要在 add() 的末尾保留 b1 的地址;程序可以编译,但出现运行时错误。

这是我的代码:

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

char *title[]= {"a", "b", "c"};
int bookNum[]= {1, 2, 3};

typedef struct
{
char *BookName;
int BookNumber;
}Book;

static void add(Book *b1, char *book, int num)
{
static int count = 0;
/*trying to create new book struct and give the right address*/
Book *b2 = (Book*) malloc (sizeof(Book));
b2 = b1;

b2->BookName = book;
b2->BookNumber = num;
count++
}

int main(int argc, char **argv)
{
Book *books[3];

for (int i = 0; i < 3; i++)
add(books[i], title[i], bookNum[i]);


for (int i = 0; i < 3; i++)
printf("Name: %s --- Age: %i \n", books[i]->BookName, books[i]->BookNumber);

return 0;
}

最佳答案

你非常接近:你需要将指针传递给指针,然后反转赋值:

static void add(Book **b1, char *book, int num) // Take pointer to pointer
{
static int count = 0;
/*trying to create new book struct and give the right address*/
Book *b2 = malloc (sizeof(Book)); // Don't cast malloc, C lets you do it
*b1 = b2; // <<== Assign to what's pointed to by b1, not to b2

b2->BookName = book;
b2->BookNumber = num;
count++
}

add() 的调用应该如下所示:

add(&books[i], title[i], bookNum[i]);    
// ^
// |
// Pass the address of the pointer

关于c - 在 C 中使用函数填充的指向结构的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40432555/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com