4

我试图了解我的代码是否正确。我需要声明一个指向结构的指针数组,创建一个新结构并分配值并打印它们。在我看来,我没有正确声明指针数组。我需要知道我做错了什么。谢谢我得到这个编译错误:错误:'people' undeclared (first use in this function) And I've try to insert struct data *list; 进入 main 但它不起作用

     char *book[] = { "x", "y", "z",};
     int number[] = { 1, 2, 3};

     struct data = { char *bookname; int booknumber;};

     function(char *x, int y)
     {
       static int count;

       struct data *list[3];

       //creating a new struct 
       list[count] = (struct data*) malloc( sizeof(struct data) );

       //assigning arguments
       list->bookname = x;
       list->booknumber = y;

       count++;
     }

     int main()
     {
       struct data *list[3];

       int i;
       for(i = 0; i < 3; i++)
       {
         function(book[i], number[i]);

         printf("name: %c number: %d", list[i]->bookname, list[i]->booknumber);
       }
4

4 回答 4

3

既然你想要数组,你需要声明数组:

char *book[] = { "x", "y", "z",};
int number[] = { 1, 2, 3};

另一个问题是

list = (struct data*) malloc( sizeof(struct data) );

//assigning arguments
list[count]->bookname = ...

在这里,list总是只有一个元素。因此,如果count不是0,您将访问一个超出范围的数组!

于 2012-07-19T15:41:16.003 回答
2

请更改以下代码

    // declaring array of pointers to structs //         
     struct data *list;         
    //not compiling        
    //struct data *list[3]; ---> There is no problem with this statement.        
   //creating a new struct         
   list = (struct data*) malloc( sizeof(struct data) );  ---> //This statement should compilation error due to declaration of struct data *list[3]

struct data *list[100]; //Declare a array of pointer to structures  
//allocate memory for each element in the array
list[count] = (struct data*) malloc( sizeof(struct data) ); 
于 2012-07-19T15:57:27.870 回答
0

我认为你应该写:

char *book[] = { "x", "y", "z"};

因为在您的情况下,您声明了一个字符数组并用指针填充它,这实际上没有任何意义。

在上面的代码行中,它只是意味着“声明一个指针数组”。

希望它有所帮助...

于 2012-07-19T15:42:04.800 回答
0

这些是您的程序中的错误

struct data = { char *bookname; int booknumber;};

“=”不应该在那里

list = (struct data*) malloc( sizeof(struct data) );
list[count]->bookname = x;
list[count]->booknumber = y;

在这里你为单个列表创建空间,所以你不能做 list[count]-> bookname,它应该是 list->bookname。与 booknumber 相同,
并且 list 是本地功能,您无法在 main 中访问它。

于 2012-07-19T15:56:38.117 回答