M
Me Alone
Hello list:
I am working on a C assignment. I am to declare a (pointer to pointer
to int), allocate memory for pointer and data, and print some output.
Problem (I think): The memory addresses printed don't look right. Would
any one be so kind to take a look at my code and explain why are the
addresses for the lists printed in "less than optimal" sequence?
Thanks in advance,
Ron
##########################################
#include <stdio.h>
#define T1 2
#define T2 5
main()
{
int i, j, **ptr;
if ((ptr = (int**)malloc(T1 * sizeof(int*))) == NULL)
{
error("Error encountered, will exit now.");
exit(0);
}
if ((*ptr = (int*)malloc(T1 * T2 * sizeof(int))) == NULL)
{
error("Error encountered, will exit now.");
exit(0);
}
for(i=0;i<T1;i++)
{
printf("\nData in table (%d).\n", i);
printf("**ptr addr\t*ptr addr\tvalue\n");
printf("=====================================\n");
for(j=0;j<T2;j++)
{
if(i > 0)
{
*(ptr+i+j) = j + T2;
printf("%X\t%X\t%d\n", &ptr+i, &ptr+i+j, (ptr+i+j));
} else {
*(ptr+i+j) = j;
printf("%X\t%X\t%d\n", &ptr+i, &ptr+i+j, *(ptr+i+j));
}
}
}
printf("\n");
}
// Output of program
Data in table (0).
**ptr addr *ptr addr value
=====================================
BFF06C84 BFF06C84 0
BFF06C84 BFF06C88 1
BFF06C84 BFF06C8C 2
BFF06C84 BFF06C90 3
BFF06C84 BFF06C94 4
Data in table (1).
**ptr addr *ptr addr value
=====================================
BFF06C88 BFF06C88 5
BFF06C88 BFF06C8C 6
BFF06C88 BFF06C90 7
BFF06C88 BFF06C94 8
BFF06C88 BFF06C98 9
I am working on a C assignment. I am to declare a (pointer to pointer
to int), allocate memory for pointer and data, and print some output.
Problem (I think): The memory addresses printed don't look right. Would
any one be so kind to take a look at my code and explain why are the
addresses for the lists printed in "less than optimal" sequence?
Thanks in advance,
Ron
##########################################
#include <stdio.h>
#define T1 2
#define T2 5
main()
{
int i, j, **ptr;
if ((ptr = (int**)malloc(T1 * sizeof(int*))) == NULL)
{
error("Error encountered, will exit now.");
exit(0);
}
if ((*ptr = (int*)malloc(T1 * T2 * sizeof(int))) == NULL)
{
error("Error encountered, will exit now.");
exit(0);
}
for(i=0;i<T1;i++)
{
printf("\nData in table (%d).\n", i);
printf("**ptr addr\t*ptr addr\tvalue\n");
printf("=====================================\n");
for(j=0;j<T2;j++)
{
if(i > 0)
{
*(ptr+i+j) = j + T2;
printf("%X\t%X\t%d\n", &ptr+i, &ptr+i+j, (ptr+i+j));
} else {
*(ptr+i+j) = j;
printf("%X\t%X\t%d\n", &ptr+i, &ptr+i+j, *(ptr+i+j));
}
}
}
printf("\n");
}
// Output of program
Data in table (0).
**ptr addr *ptr addr value
=====================================
BFF06C84 BFF06C84 0
BFF06C84 BFF06C88 1
BFF06C84 BFF06C8C 2
BFF06C84 BFF06C90 3
BFF06C84 BFF06C94 4
Data in table (1).
**ptr addr *ptr addr value
=====================================
BFF06C88 BFF06C88 5
BFF06C88 BFF06C8C 6
BFF06C88 BFF06C90 7
BFF06C88 BFF06C94 8
BFF06C88 BFF06C98 9