1

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.

2
  • Yes it is - in fact, you could use ptr1 instead of ptr and not bother with the malloc and free Commented Jun 28, 2015 at 18:35
  • always check (!=NULL) the returned value from malloc() and family of functions. Otherwise any dereference of the returned value will result in access to addresses around 0. This is undefined behaviour and can/will lead to a seg fault event Commented Jun 28, 2015 at 19:29

2 Answers 2

3

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

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

int main( void ) 

At least it shall have return type int.

Sign up to request clarification or add additional context in comments.

Comments

0

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

I.E.

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

1 Comment

*ptr1=*ptr; is valid as long as ptr is a pointer to a structure smaller then or of equal size of the structure pointed by ptr1. in this case they are pointing to the same type. So it is valid (even though obviously not needed, memcpy also is not needed by the way see @vlad-from-Moscow answer).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.