I'm trying to return an array and its length from one function to another. I've learned that I can't simply determine the size of the returning array in the parent function with sizeof() because arrays are reduced to pointers when passed as parameters. I've figured out that I can use a struct to return the array pointer and size to the parent function, so that's what I'm attempting.
The array is of type unsigned char* since I'm working with memory addresses. The array appears fine before it is sent to the struct. Once I try to reference the array via the struct in a parent function, all of the memory addresses are split up. I have a hunch that struct padding could be the problem.
I've written some prints to really analyze what's going on.
struct arrayPasser{
int length;
unsigned char *arr;
};
unsigned char *arr[arrLength]; /*array of pointers*/
/*filling out the array with addresses*/
struct arrayPasser pass;
pass.length=arrLength;
pass.arr=&arr;
printf("pass.arr: %#x\n", pass.arr); /*print array location*/
printf("*(&arr): %#x\n", *(&arr));
printf("**(&arr): %#x\n", **(&arr));
/*original array*/
printf("arr[0] %#x\n", arr[0]);
printf("arr[1] %#x\n", arr[1]);
printf("arr[2] %#x\n", arr[2];
/*referencing array through struct*/
printf("0 offset: %#x\n", *pass.arr);
printf("1 offset: %#x\n", *(pass.arr+1));
printf("2 offset: %#x\n", *(pass.arr+2));
printf("3 offset: %#x\n", *(pass.arr+3);
printf("4 offset: %#x\n", *(pass.arr+4));
printf("5 offset: %#x\n", *(pass.arr+5));
printf("6 offset: %#x\n", *(pass.arr+6));
printf("7 offset: %#x\n", *(pass.arr+7));
printf("pass.arr[0]: %#x\n", pass.arr[0]);
printf("pass.arr[1]: %#x\n", pass.arr[1]);
printf("pass.arr[2]: %#x\n", pass.arr[2]);
printf("pass.arr[3]: %#x\n", pass.arr[3]);
printf("pass.arr[4]: %#x\n", pass.arr[4]);
printf("pass.arr[5]: %#x\n", pass.arr[5]);
printf("pass.arr[6]: %#x\n", pass.arr[6]);
printf("pass.arr[7]: %#x\n", pass.arr[7]);
Output (notice how arr[0] is a full 32-bit address but pass.arr[0] is only one byte of the 32-bit address) :
arr[0] 0x4affb000
arr[1] 0x4affd000
arr[2] 0x4affc000
pass.arr: 0x58dcf10
*(&arr): 0x58dcf10
**(&arr): 0x4affb000
0 offset: 0
1 offset: 0xb0
2 offset: 0xff
3 offset: 0x4a
4 offset: 0
5 offset: 0xd0
6 offset: 0xff
7 offset: 0x4a
pass.arr[0]: 0
pass.arr[1]: 0xb0
pass.arr[2]: 0xff
pass.arr[3]: 0x4a
pass.arr[4]: 0
pass.arr[5]: 0xd0
pass.arr[6]: 0xff
pass.arr[7]: 0x4a