malloc and array

Discussion in 'C Programming' started by lovecreatesbeauty, Jun 12, 2010.

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

    --
    sent on Nexus One
    lovecreatesbeauty, Jun 12, 2010
    #1
    1. Advertising

  2. On Jun 12, 9:04 pm, 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];
    > 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
    lovecreatesbeauty, Jun 12, 2010
    #2
    1. Advertising

  3. lovecreatesbeauty

    Eric Sosman Guest

    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
    lid
    Eric Sosman, Jun 12, 2010
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. John
    Replies:
    13
    Views:
    699
  2. ravi
    Replies:
    0
    Views:
    449
  3. Peter
    Replies:
    34
    Views:
    1,936
    Richard Tobin
    Oct 22, 2004
  4. porting non-malloc code to malloc

    , Feb 18, 2005, in forum: C Programming
    Replies:
    3
    Views:
    479
    Walter Roberson
    Feb 19, 2005
  5. Johs32

    to malloc or not to malloc??

    Johs32, Mar 30, 2006, in forum: C Programming
    Replies:
    4
    Views:
    320
    Captain Winston
    Mar 30, 2006
Loading...

Share This Page