c - 如何在函数定义中访问 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);
}
}
解决方案
如果您有一个结构指针示例:struct structName *pToAStruct;
,要访问字段的值,请使用->
如下运算符 : var = pToAStruct->field
。例如,具有var
和field
具有相同类型int
。
如果你有一个直接的结构变量,那么使用.
运算符。例子:struct structName AStruct;
var = AStruct.field;
请注意,在这些示例中,我假设您已在需要时分配内存/初始化结构。
推荐阅读
- python-3.x - 对包含元组列表的 pandas DataFrame 列中的第一个元素求和返回 ValueError
- puppeteer - 无法抓取网站运行代码时出错。TimeoutError: Navigation Timeout Exceeded: 超过 30000ms
- javascript - 如何阻止用户在某个点滚动?
- reactjs - 设置用户后组件不会重新渲染
- java - 在 BouncyCastle BCFKS 密钥库中存储 X25519 密钥对
- android - 拖动时如何更新 SeekBarPreference 值?
- redis - 下划线作为redis中的键
- html - 角度材料步进器无法与角度形式的 mat-grid-list 一起正常工作
- ios - 我有一个表格视图单元格,我从视图控制器调用一个函数,该函数位于表格视图单元格中,如图所示,但它显示错误
- events - Linux:使用 entr 和 mutt 创建新文件时发送电子邮件