指向在C中使用函数填充的结构的指针数组
我正在尝试制作一个程序,它填充指向struct的指针数组,但使用一个函数来完成。 我相信我对指针做了一些错误,因为我需要在add()的末尾保留b1的地址; 程序可以编译,但我得到一个运行时错误 这是我的代码:指向在C中使用函数填充的结构的指针数组,c,pointers,structure,C,Pointers,Structure,我正在尝试制作一个程序,它填充指向struct的指针数组,但使用一个函数来完成。 我相信我对指针做了一些错误,因为我需要在add()的末尾保留b1的地址; 程序可以编译,但我得到一个运行时错误 这是我的代码: #include <stdio.h> #include <stdlib.h> char *title[]= {"a", "b", "c"}; int bookNum[]= {1, 2, 3}; typedef struct { char *BookName;
#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;
}
#包括
#包括
字符*标题[]={“a”、“b”、“c”};
int bookNum[]={1,2,3};
类型定义结构
{
字符*书名;
国际书号;
}书;
静态空添加(Book*b1,char*Book,int num)
{
静态整数计数=0;
/*正在尝试创建新书结构并提供正确的地址*/
Book*b2=(Book*)malloc(sizeof(Book));
b2=b1;
b2->BookName=book;
b2->BookNumber=num;
计数++
}
int main(int argc,字符**argv)
{
书*书[3];
对于(int i=0;i<3;i++)
增加(图书[i],标题[i],图书编号[i]);
对于(int i=0;i<3;i++)
printf(“名称:%s--年龄:%i\n”,图书[i]->图书名称,图书[i]->图书编号);
返回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(&books[i], title[i], bookNum[i]);
// ^
// |
// Pass the address of the pointer