Terry Andersen said:
Thanks a lot. Would this mean that testchar, testshort and anothertestchar
are stored from memory location mymemlocation and further? If mymemlocation
would be like:
unsigned char TheBuffer[100];
//and you called the testfunc with:
testfunc(TheBuffer[50]);
No. First of all you would not pass TheBuffer to testfunc() with the
subscript on it. It would be passed as
testfunc(TheBuffer);
instead. The name of an array is a pointer to the first value, which you
could later iterate over.
Would TheBuffer then look like:
TheBuffer[50] = 0x55
TheBuffer[51] = 0xFF
TheBuffer[52] = 0xFF
TheBuffer[53] = 0x11
No. I think you mean: would the buffer[index] hold the values from the
function as array indexes. No.
With this code, you are now overwriting the boundary of your array, which
ends at 49. Remember that arrays start from 0, and go to length-1. So if I
had an array like:
char array[45];
I can only access array[0] to array[44].
If you access anything outside of your array's range, it is undetermined
behavior, but most likely you will overwrite another program's (running on
your machine) data causing a crash or something nastier.
To get back to your question about whether the members from the struct are
part of the array, no. You are attempting to pass an unsigned char to your
function as a form of memory reservation. Instead use:
struct mystruct p_yourstruct* = (struct mystruct) malloc(sizeof(mystruct));
to get the memory. For example:
---------------------------------------------
struct mystruct
{
unsigned char testchar;
unsigned short testshort;
unsigned char anothertestchar;
};
struct mystruct* mem_location = (struct mystruct) malloc(sizeof(mystruct));
void testfunc(struct mystruct* mymemlocation)
{
thedata->testchar = 0x55;
thedata->testshort = 0xFFFF;
thedata->anothertestchar = 0x11;
};
-----------------------------------------------------------------------
malloc() allocates memory for your struct. You need to call
free(mem_location) to free up the memory before your program terminates, or
else you will get memory leak.
To use the code you would pass:
testfunc(mem_location);
and then you could goof off with the variables.
Try not to mix apples and oranges. The only thing you should pass to hold a
struct is another struct of the same type. It would be like passing a car
variable to a function that uses the car to hold a mansion.
Any more questions? =)