Velocity Reviews > malloc and array

malloc and array

lovecreatesbeauty
Guest
Posts: n/a

 06-12-2010
#define N 100
#define LEN 1024
char a1[N][LEN];
char *m2 = malloc(N * LEN);
char *c3 = calloc(N, LEN);

char *p1 = (char*) &a1[1][0];
char *p2 = m2[1 * LEN + 0];
char *p3 = c3[1 * LEN + 0];

suppose allocate memory successfully, do p1, p2, p3 all point to the
1024th character, the beginning of the second row in array terms?

--
sent on Nexus One

lovecreatesbeauty
Guest
Posts: n/a

 06-12-2010
On Jun 12, 9:04*pm, lovecreatesbeauty <(E-Mail Removed)>
wrote:
> #define N 100
> #define LEN 1024
> char a1[N][LEN];
> char *m2 = malloc(N * LEN);
> char *c3 = calloc(N, LEN);
>
> char *p1 = (char*) &a1[1][0];
> char *p2 = m2[1 * LEN + 0];
> char *p3 = c3[1 * LEN + 0];
>
> suppose allocate memory successfully, do p1, p2, p3 all point to the
> 1024th character

in their memory blocks respectively

>, the beginning of the second row in array terms?
>
> thank you for your time.
>
> --
> sent on Nexus One

Eric Sosman
Guest
Posts: n/a

 06-12-2010
On 6/12/2010 9:04 AM, lovecreatesbeauty wrote:
> #define N 100
> #define LEN 1024
> char a1[N][LEN];
> char *m2 = malloc(N * LEN);
> char *c3 = calloc(N, LEN);
>
> char *p1 = (char*)&a1[1][0];

Why the cast?

> char *p2 = m2[1 * LEN + 0];
> char *p3 = c3[1 * LEN + 0];
>
> suppose allocate memory successfully, do p1, p2, p3 all point to the
> 1024th character, the beginning of the second row in array terms?

No, because the declarations of p2 and p3 won't compile. If
you insert the missing address-of operators:

char *p2 = &m2[1 * LEN + 0];
char *p3 = &c3[1 * LEN + 0];

.... or rewrite as arithmetic on pointers:

char *p2 = m2 + 1 * LEN + 0;
char *p3 = c3 + 1 * LEN + 0;

.... the answer changes to "Yes."

--
Eric Sosman
http://www.velocityreviews.com/forums/(E-Mail Removed)lid