首页 > 解决方案 > 如何在函数定义中访问 Struct 数组的字段

问题描述

我是编程新手,我很难学习 DMA 并尝试同时使用结构和指针。我正在开发一个程序,该程序接收有关书籍的信息并将作者和标题存储在要显示的结构数组中,它需要 DMA 将字符串存储在结构中。

我最难理解和尝试修复的部分是当我尝试访问函数定义中的 Struct 数组的字段时,例如:

void getInfo(struct BookInfo *pbook, char author[], char title[])
{
     //creating memory for strings 
     pbook.author = (struct BookInfo*) malloc((strlen(author) +1) * sizeof(char));       
     pbook.title = (struct BookInfo*) malloc((strlen(title) +1) * sizeof(char)); 

     //copying info into the heap
     strcopy(pbook.author, author);
     strcopy(pbook.title, title);

}


I would really appreciate your help in any way, thanks in advance

这是我的完整代码:

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

#define size 5   //size is the total number of elements in the array

//declaration of struct
struct BookInfo {

    char* author;
    char* title;
};

//prototypes
void getInfo(struct BookInfo *pbook, char author[], char title[]);
void printInfi(struct BookInfo book[]);

int main() {

    struct BookInfo myBook[size];    //declare an array.
    char author[40] = { '0' };   //temp strings to store input from user
    char title[50] = { '0' };


    //get input from user
    printf("Enter author name: ");
        fgets(author, 40, stdin);

    printf("Enter book title name: ");
        fgets(title, 50, stdin);


   // call function to store info (dma) individually in array, loop 5 times do fill struct array 
     for(int i =0; i < size; i++)
         {
             void getInfo(struct BookInfo myBook, author, title);
         }

   // call function to print all info from array, call one time
      void printInfi(struct BookInfo myBook);

   // Free space from dma
       for(int i=0; i < size; i++)
           {
              free(myBook[i].author);
              free(myBook[i].title); 
           }

    return 0;
}


void getInfo(struct BookInfo *pbook, char author[], char title[])
{
     //creating memory for strings 
     pbook.author = (struct BookInfo*) malloc((strlen(author) +1) * sizeof(char));       
     pbook.title = (struct BookInfo*) malloc((strlen(title) +1) * sizeof(char)); 

     //copying info into the heap
     strcopy(pbook.author, author);
     strcopy(pbook.title, title);

}

void printInfo(struct BookInfo book[])
{
     for(int i = 0; i < size; i++)   
         {
             printf("Title: %s, Author: %s\n", book[i].author, book[i].title);
         }

}

标签: carrayspointersstructdynamic-memory-allocation

解决方案


如果您有一个结构指针示例:struct structName *pToAStruct;,要访问字段的,请使用->如下运算符 : var = pToAStruct->field。例如,具有varfield具有相同类型int

如果你有一个直接的结构变量,那么使用.运算符。例子:struct structName AStruct; var = AStruct.field;

请注意,在这些示例中,我假设您已在需要时分配内存/初始化结构。


推荐阅读