malloc and array

L

lovecreatesbeauty

#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?

thank you for your time.
 
L

lovecreatesbeauty

#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
 
E

Eric Sosman

#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."
 

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,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top