D
Durango2008
Hello,
I know some C but still learning pointers and I have a question regarding
arrays using pointers.
I compiled the following code but I am confused by it:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int **a;
char **b;
int i;
a = malloc(2 * sizeof(int *));
for(i = 0; i < 2; i++)
a = malloc(13 * sizeof(int));
b = malloc(2 * sizeof(char *));
for(i = 0; i < 5; i++)
b = malloc(13 * sizeof(char));
a[0][0] = 44;
b[0][0] = 55;
printf("a[0][0] = %d\n",a[0][0]);
printf("(int)*(a) = %d\n", (int)*(a+4));
printf("b[0][0] = %d\n",b[0][0]);
printf("(char)*(b) = %d\n", (int)*(b+4));
return 0;
}
I compiled this in both Linux(Redhat) using GCC and Windows XP using
Code::Blocks.
In Linux it gave the following results:
a[0][0] = 44
(int)*(a) = 44
b[0][0] = 55
b[0][0] = 55
My first question is why do you need to add 4 to the pointer index to get
the correct result?
In Windows XP it gave the following results:
a[0][0] = 44
(int)*(a) = 44
b[0][0] = 55
(char)*(b) = 4079600
It clearly shows that the final value is wrong and pointer reference issue.
What I need to know is how can dereference this 2D array properly and what
are some easier ways of obtaining
the value of a 2D array using pointers without using indexing?
Thank you for your help.
I know some C but still learning pointers and I have a question regarding
arrays using pointers.
I compiled the following code but I am confused by it:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int **a;
char **b;
int i;
a = malloc(2 * sizeof(int *));
for(i = 0; i < 2; i++)
a = malloc(13 * sizeof(int));
b = malloc(2 * sizeof(char *));
for(i = 0; i < 5; i++)
b = malloc(13 * sizeof(char));
a[0][0] = 44;
b[0][0] = 55;
printf("a[0][0] = %d\n",a[0][0]);
printf("(int)*(a) = %d\n", (int)*(a+4));
printf("b[0][0] = %d\n",b[0][0]);
printf("(char)*(b) = %d\n", (int)*(b+4));
return 0;
}
I compiled this in both Linux(Redhat) using GCC and Windows XP using
Code::Blocks.
In Linux it gave the following results:
a[0][0] = 44
(int)*(a) = 44
b[0][0] = 55
b[0][0] = 55
My first question is why do you need to add 4 to the pointer index to get
the correct result?
In Windows XP it gave the following results:
a[0][0] = 44
(int)*(a) = 44
b[0][0] = 55
(char)*(b) = 4079600
It clearly shows that the final value is wrong and pointer reference issue.
What I need to know is how can dereference this 2D array properly and what
are some easier ways of obtaining
the value of a 2D array using pointers without using indexing?
Thank you for your help.