strange pointer problems

B

Bruno van Dooren

Hi All,

i have some (3) different weird pointer problems that have me stumped. i
suspect that the compiler behavior is correct because gcc shows the same
results.

----------------------------------------------
//example 1:
typedef int t_Array[10];
int _tmain(int argc, _TCHAR* argv[])
{
t_Array array;
array[0] = 123;
array[9] = 321;

t_Array *ptrArray[] = {&array};
t_Array *element = ptrArray[0];

printf("array = 0x%08x, ptrArray[0] = 0x%08x, element = 0x%08x, *element =
0x%08x\n",
array, ptrArray[0], element, *element);

printf("array[9] = %d, (*element)[9] = %d, element[9] = %d\n",
array[9], (*element)[9], element[9]);

return 0;
}

now according to the print statements, the different pointers all point to
the same thing, even though 'element' is dereferenced at one place, and not
dereferenced at another place. if i try to print a value from the array, i
get 2 different results.
??
----------------------------------------------
example 2:
typedef int t_Array[10];
void function(t_Array Array)
{
t_Array *ptrArray[] = {&Array}; //error
}
int _tmain(int argc, _TCHAR* argv[])
{
t_Array array;
t_Array *ptrArray[] = {&array}; //no error
return 0;
}
the 2 declarations of the arrays look the same to me, but 1 gives an error,
and the other one doesn't. i have looked up the documentation of that
error, but that didn't shine much light.
??

----------------------------------------------
example 3:
typedef int t_Array[10];
void function(t_Array Array)
{
t_Array *element = NULL;
void * ptrArray[] = {NULL};

ptrArray[0] = &Array; //first element should be pointer to a t_Array
element = (t_Array *)ptrArray[0];
printf("Weird Failure: (*element)[9] = %d\n", (*element)[9]);

ptrArray[0] = Array; //first element should be Array itself
element = (t_Array *)ptrArray[0];
printf("Weird Success: (*element)[9] = %d\n", (*element)[9]);
}
int _tmain(int argc, _TCHAR* argv[])
{
t_Array array;
array[9] = 321;
function(array);
return 0;
}
this is what really caused my headaches. i used void pointers to get rid of
the error, but that caused weird behavior. in the first situation in
'function', i expect to dereference a pointer to end up with an array, but
that clearly is not what happens.
in the second situation i expect to do something illegal: ie to use a
pointer to an array as the array itself, and somehow that seems to work.
what do i miss here?

i would be very grateful for some light on this murky behavior (or at least
my murky understanding).

kind regards,
Bruno.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,158
Latest member
Vinay_Kumar Nevatia
Top