我是一名编程新手,我在学习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;
在这些例子中,我假设你已经分配了内存 在需要的时候初始化了结构。