Tuesday, July 28, 2009

C Programming: How do I set one pointer to a structure equal to an existing one?

If you just want Action to point to Enemy, you do:





Character *Action;





Action = Enemy;





If you want a real copy you need to reserve memory for Action and do the copy like this:





Character Action;





memcpy(%26amp;Action, Enemy, sizeof(Character));

C Programming: How do I set one pointer to a structure equal to an existing one?
Don't do it! Use a variable instead. I had to virtually offer a colleague violence when he insisted making the "pointer to a pointer" thing work, he was at it for 3 days. It took him 45mins with a variable once he saw the light. You've got buckets of memory these days, use it.
Reply:No problem


typedef struct


{


int a;


int b;


}myType;





myType *x;


myType *y;





x = (myType *)malloc(sizeof(myType));


y = (myType *)malloc(sizeof(myType));





x-%26gt;a = 3;


x-%26gt;b = 5;





*y = *x;





that will copy all of the x data into the y memory.





Your example has:


*Enemy = *Action;





That's backward, you haven't assigned Action yet.


Also you haven't given it memory to Enemy or Action.


you need to malloc space for both.





The other poster is correct too. You can either copy the


structure using the derefernce "*" or using memcpy.





Oops, sorry you're just assigning the ptr for Enemy still need memory for action.





---


just did this in Visual Studio express, it works fine:





#include "stdafx.h"


#include "string.h"


#include "stdlib.h"





typedef struct Man {


char Name[31];


int Number;


}Character;








int _tmain(int argc, _TCHAR* argv[])


{


Character Bob;


Character *Enemy;


Character *Action;





Bob.Number=110;


strncpy(Bob.Name, "Bob", 31);





Enemy=%26amp;Bob;





Action = (Character *)malloc(sizeof(Character));





*Action = *Enemy;





return 0;


}
Reply:Try here for info


http://www.techtutorials.net/





http://www.rickmaybury.com/





http://www.theeldergeek.com/


http://www.good-tutorials.com/


http://www.digitaljuice.com/


http://www.tutorialkit.com/


http://www.codestyles.com/


http://www.sitecube.com/website/promo_bw...


No comments:

Post a Comment