我需要编写一个程序,其中包含两个字段的结构:整数和字符串 . 接下来我需要编写一个动态分配这个结构的函数,并将int和string作为参数传递给分配的结构 . 此函数还将返回指向新建结构的指针 . 该程序的第二个元素应该是将struct指针作为参数的函数,然后在屏幕上打印所有文件,然后释放struct的内存 . 这是我能想到的最好的 .
#include <stdio.h>
#include <stdlib.h>
struct str{
int num;
char text[20];
};
struct str* return_address(int *num, char *text){
struct str* new_struct=malloc(sizeof(struct str));
new_struct->num=num;
new_struct->text[20]=text;
return new_struct;
};
void release(struct str* s_pointer){
printf("%d %s", s_pointer->num, s_pointer->text);
free(s_pointer);
};
int main()
{
struct str* variable=return_address(1234, "sample text");
release(variable);
return 0;
}
1 回答
你的阵列很小,也不是动态的 . 如果你正在使用
malloc()
分配,为什么不动态分配一切?您无法分配给阵列 .
num
成员,我想这是为了存储“字符串”的长度,正被分配一个指针,这不是你想要的 . 而且,仅在非常特殊的情况下定义行为时,指定一个整数,编译器应该警告你,除非你关闭警告 .也许你想要这个,