【发布时间】:2016-11-04 22:25:40
【问题描述】:
我正在尝试编写一个程序来填充指向 struct 的指针数组,但使用函数来执行此操作。 我相信我对指针做错了,因为我需要在 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;
}
【问题讨论】: