C 函数间传递结构

C 函数间传递结构,c,structure,C,Structure,我刚刚写了一个小程序来处理结构。这个程序运行得很好,但我有一句话有点怀疑。有人能澄清一下吗 #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(si

我刚刚写了一个小程序来处理结构。这个程序运行得很好,但我有一句话有点怀疑。有人能澄清一下吗

#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);
}
#包括
#包括
#包括
结构mystr
{
INTA;
浮球b;
char a1[10];
};
void fun(结构mystr*ptr1)
{
结构mystr*ptr;
ptr=malloc(sizeof(struct mystr));
ptr->a=10;
ptr->b=1662.3456;
strcpy(ptr->a1,“xxxxxx”);
*ptr1=*ptr;/*此分配

*ptr1=*ptr;  /* <<<<<<<<<<<- This assignment is fine? */
也不是在结构对象定义之后使用memset

struct mystr var1;
memset(&var1,0,sizeof(struct mystr));
你可以写得很简单

struct mystr var1 = { 0 };
考虑到C中的函数main应声明为

int main( void )

在张贴的代码中至少应有返回类型int.

,此行:

*ptr1=*ptr;
这是胡说八道

它不复制两个结构的内容

要复制内容,请使用memcpy(pDestination、pSource、numBytesToCopy)


是的,它是-事实上,您可以使用ptr1而不是ptr,并且不必麻烦malloc和freeally检查malloc()返回的值(!=NULL)和函数系列。否则,对返回值的任何取消引用都将导致访问0左右的地址。这是未定义的行为,并且可能/将导致seg故障事件
*ptr1=*ptr;
有效,只要
ptr
是指向小于或等于
ptr1。在本例中,它们指向相同的类型。因此它是有效的(尽管显然不需要,memcpy也不需要,请参见莫斯科答案中的@vlad)。
*ptr1=*ptr;
memcpy( ptr1, ptr, sizeof( struct mystr ) );