View previous topic :: View next topic |
Author |
Message |
hunterc
Joined: 29 Nov 2004 Posts: 2
|
passing stucture pointers |
Posted: Mon Nov 29, 2004 10:22 pm |
|
|
I'm writing code for an 18LF4520. For previous PICs' I've tended to use globals to keep things simple and because I've never really been pushing the limits of the RAM. For this project I will need all the RAM I can get and decided to be tidy from the outset. I want to grab memory when necessary and then release it when I return to main(). In the following code I'm creating a structure in func1 and then using strcpy to copy "xx" and "yy" into the two elements. Stepping through the code with an ICD2 and this is working fine. I then pass the pointer to the structure to func2 as a parameter. funct2 then uses stncpy to change the elements in the structure. This does not work. Any ideas? Am I doing something dumb, or am I up against a 'feature' of the compiler?
/***** CODE EXAMPLE *****/
typedef struct {char str1 [2]; char str2 [2];} play;
char stra[] = "aa";
char strb[] = "bb";
void func2 (play *structptr)
{
strcpy (structptr->str1, stra);
strcpy (structptr->str2, strb);
}
void func1 (void)
{
char strc[] = "xx";
char strd[] = "yy";
play test, *testptr;
testptr = &test;
strcpy (testptr->str1, strc);
strcpy (testptr->str2, strd);
func2 (testptr);
delay_cycles (2);
}
void main (void)
{
func1();
} |
|
|
Mark
Joined: 07 Sep 2003 Posts: 2838 Location: Atlanta, GA
|
|
Posted: Mon Nov 29, 2004 11:04 pm |
|
|
Quote: | a 'feature' of the compiler?
|
I will say it is not a "feature" or bug as some would call it.
In your typedef
Code: |
char str1 [2];
char str2 [2];
|
but
code]
char stra[] = "aa";
char strb[] = "bb";
[/code]
These actually take up 3 bytes. Remember the Null at the end. So change your typedef to
Code: |
typedef struct
{
char str1 [3];
char str2 [3];
} play;
|
and give it a shot. |
|
|
hunterc
Joined: 29 Nov 2004 Posts: 2
|
|
Posted: Mon Nov 29, 2004 11:16 pm |
|
|
Hi Mark,
thanks for the quick response. I actually figured it out just after I posted. But, I still don't understand the mechanism. I would have expected it to mechanically overwrite the elements in the structure with three instead of two characters as I think it uses the null termination from the source string not the destination. It appeared to do nothing, just left "xx' and "yy" in the elements, and yet it did not raise an error or warning. Weird huh!
Anyway, thanks again for your help.
Cheers,
Colin. |
|
|
Mark
Joined: 07 Sep 2003 Posts: 2838 Location: Atlanta, GA
|
|
Posted: Mon Nov 29, 2004 11:30 pm |
|
|
The pointer gets screwed up in func1 from the copy. The NULL gets copied into the pointer. So it does copy, just not where you think |
|
|
|