为指向函数内部结构的指针分配内存 [英] Allocate memory for a pointer to a struct inside a function
问题描述
我正在尝试编写一个单独的程序,该程序调用一个函数为一定数量的学生"结构动态分配内存.
I am trying to write a separate program that calls a function to dynamically allocate memory for a certain number of "student" structs.
我的主程序太大而无法处理,所以我创建了一个较小的程序来帮助我更轻松地弄清楚我在做什么:
My main program was too large to mess with so I created a smaller program to help me more easily figure out what I'm doing:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "memtest.h"
void structMemInit(myName **);
int main(void){
myName *myNameIs;
structMemInit(&myNameIs);
printf("%s\n", myNameIs[1].name);
return 0;
}
void structMemInit(myName **myNameIs){
*myNameIs = (myName *) calloc(5, sizeof(myName));
if(myNameIs == NULL){
printf("allocating memory didn't work!\n");
exit(1);
}
else if(myNameIs != NULL)
(*myNameIs)[1].name = "Zach";
}
memtest.h 文件是:
the memtest.h file is:
typedef struct{
char *name;
}myName;
以上程序试图做的就是将指向结构的指针传递给函数structMemInit"并为该结构分配干净的空间.然后为了查看它是否有效,我将变量 char 设置为一个名称.在这一切发生之后,您离开函数并返回主函数.然后我在结构中打印名称以显示它有效.
All the above program is trying to do is pass a pointer to a struct into the function "structMemInit" and allocate clean space for the struct. Then to see show that it worked, I am setting the variable char to a name. After all this happens, you leave the function and go back to main. Then I print the name in the struct to show it worked.
运行时,程序总是给出段错误.
When run, the program always gives a segfault.
如果你想知道为什么我有一个单独的 .h 文件,我的实际程序要大得多,并且有几个全局声明的结构,我的老师要求我为这些结构保留一个单独的 .h.
In case you are wondering why I have a separate .h file, my actual program is much larger and has several globally declared structs and I am required by my instructor to keep a separate .h for those structs.
谢谢!扎克
推荐答案
如果你坚持传递指针,应该是通过引用,所以它是一个指向指针的指针,因为函数itslef会修改指针中的地址.
If you insist on passing the pointer, it should be by reference, so it's a pointer to a pointer, as the function itslef will modify the address in the pointer.
如果你的函数返回一个指针,你会好得多.
You're much better off if your function returns a pointer.
//function for allocating the memory
myName *structMemInit(void)
{
myName *myNameIs = (myName *)calloc(1, sizeof(myName));
if (myNameIs == NULL) {
printf("allocating memory didn't work!\n");
exit(1);
} else { // don't repeat the negation of the condition
myNameIs->name = "Zach"; // No need for \0, it's automatic
return myNameIs;
}
}
//Usage
myName *myNameIs = structMemInit();
顺便说一句,它是 int main(void)
而不是 int main()
.
BTW it's int main(void)
not int main()
.
这篇关于为指向函数内部结构的指针分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!