简体   繁体   English

在函数之间传递结构

[英]passing structure between function

I just wrote a small program to play with structures.This program works fine but i just have small doubt in one statement.Can anyone clarify me please? 我刚刚写了一个小程序来玩结构。这个程序运行正常,但我只是在一个声明中有一点疑问。谁能澄清我好吗?

#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);
}

I know that i can just pass a pointer to the fun and print it free it. 我知道我可以通过一个指向乐趣的指针并将其打印出来。 But i just wanted this program to be this way(passing structure variable address and filling it). 但我只是希望这个程序是这样的(传递结构变量地址并填充它)。 Thanks in advance. 提前致谢。

This assignment 这个任务

*ptr1=*ptr;  /* <<<<<<<<<<<- This assignment is fine? */

is fine. 很好。 Only there is no sense to allocate dynamically one more structure that to initialize the original structure. 只有动态分配一个初始化原始结构的结构是没有意义的。 You could write the function simpler 你可以写函数更简单

void fun(struct mystr *ptr1)
{
    ptr1->a = 1 0;
    ptr1->b = 1 662.3456;
    strcpy( ptr1->a1, "xxxxxx" );
}

Also instead of using memset after the structure object definition 而不是在结构对象定义之后使用memset

struct mystr var1;
memset(&var1,0,sizeof(struct mystr));

you could write simply 你可以写简单

struct mystr var1 = { 0 };

Take into account that function main in C shall be declared like 考虑到C中的函数main应该被声明为

int main( void )

At least it shall have return type int. 至少它应该有返回类型int。

in the posted code, this line: 在发布的代码中,这一行:

*ptr1=*ptr;

is nonsense. 是胡说八道。

It does not copy the contents of the two structs. 它不会复制两个结构的内容。

to copy the contents, use memcpy( pDestination, pSource, numBytesToCopy ); 要复制内容,请使用memcpy(pDestination,pSource,numBytesToCopy);

IE IE

memcpy( ptr1, ptr, sizeof( struct mystr ) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM