我刚写了一个小程序来玩弄结构。这个程序运行良好,但我只是对一个陈述有一点疑问。有人能给我解释一下吗?
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct mystr
{
int a;
float b;
char a1[10];
};
void fun(struct mystr *ptr1)
{
struct mystr *ptr;
ptr=malloc(sizeof(struct mystr));
ptr->a=10;
ptr->b=1662.3456;
strcpy(ptr->a1,"xxxxxx");
*ptr1=*ptr; /* <<<<<<<<<<<- This assignment is fine? */
free(ptr);
}
void main()
{
struct mystr var1;
memset(&var1,0,sizeof(struct mystr));
fun(&var1);
printf("my data is %4d,%10.3f,%5s\n",var1.a,var1.b,var1.a1);
}
我知道我可以将指针传递给 fun 并免费打印它。但我只是希望这个程序是这样的(传递结构变量地址并填充它)。 提前致谢。
最佳答案
这个作业
*ptr1=*ptr; /* <<<<<<<<<<<- This assignment is fine? */
很好。只有动态分配一个更多的结构来初始化原始结构是没有意义的。你可以把函数写得更简单
void fun(struct mystr *ptr1)
{
ptr1->a = 1 0;
ptr1->b = 1 662.3456;
strcpy( ptr1->a1, "xxxxxx" );
}
也不是在结构对象定义之后使用memset
struct mystr var1;
memset(&var1,0,sizeof(struct mystr));
你可以简单地写
struct mystr var1 = { 0 };
考虑到 C 中的函数 main 应该像这样声明
int main( void )
至少它的返回类型应该是 int。
关于c - 在函数之间传递结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31103315/