Array and Pointer Tutorial

Discussion in 'C Programming' started by Tomás, May 11, 2006.

  1. Tomás

    Tomás Guest

    Some programmers treat arrays just like pointers (and some even think that
    they're exactly equivalent). I'm going to demonstrate the differences.

    Firstly, let's assume that we're working on a platform which has the
    following properties:

    1) char's are 8-Bit. ( "char" is synomonous with "byte" ).
    2) int's are 32-Bit. ( sizeof(int) == 4 ).
    3) Pointers are 64-Bit. ( sizeof(int*) == 8 ).


    First let's make two declarations:

    int main(void)
    {
    int array[5];

    int* const pointer = (int*)malloc( 5 * sizeof(int) );
    }


    Now I'll demonstrate how "array" and "pointer" are different:


    I'll start off with simple analgous expressions:

    ============================================================================
    | Expression | Type and Access Specifiers | That in English |
    ============================================================================
    | | | |
    | array | int[5] | An array of five int's.|
    | | | |
    |---------------------------------------------------------------------------
    | | |A const pointer which |
    | pointer | int* const |points to a modifiable |
    | | |int. |
    |--------------------------------------------------------------------------|
    | | |A const pointer which |
    | &array | int (* const)[5] |points to a modifiable |
    | | |array of five int's. |
    |--------------------------------------------------------------------------|
    | | |A const pointer, which |
    | &pointer | int* const* const |points to a const |
    | | |pointer, which points to|
    | | |a modifiable int. |
    ============================================================================


    Here's how "sizeof" works with them:


    ===========================================================
    | Expression | sizeof( exp ) | But Why? |
    ===========================================================
    | | | |
    | array | 20 | It's five int's. |
    | | (5 * 4) | |
    |---------------------------------------------------------|
    | | | |
    | pointer | 8 | It's just a pointer.|
    | | (just 8) | |
    |---------------------------------------------------------|
    | | | |
    | &array | 8 | It's just a pointer.|
    | | (just 8) | |
    |----------------------------------------------------------
    | | | |
    | &pointer | 8 | It's just a pointer.|
    | | | |
    | | (just 8) | |
    ===========================================================


    Okay next thing to discuss is the usage of square brackets, and the
    dereference operator. The two of these are to be used by pointers only. So
    how come we can use them with arrays, as follows?:

    array[0] = 4;

    *array = 6;

    The reason is that an expression of the following type:

    int[5]

    can implicitly convert to an expression of the following type:

    int* const

    What it does is convert to a pointer to the first element of the array.
    Therefore, the first example:

    array[0] = 4;

    implicitly converts "array" to a normal pointer, then uses chain brackets to
    access memory at a certain offset from the original address.

    Also the second example:

    *array = 6;

    implicitly converts "array" to a normal pointer, then dereferences it.


    NOTE: You must remember that an array implicitly converts to a pointer to
    its first element, NOT to a pointer to the array. This fact has a few
    implications. Here's one such implication:


    *(array + 3) = 6;


    What the above line of code does is the following:

    1) Implicitly converts "array" to an: int* const
    2) Adds 3 * sizeof(int) to the address.
    3) Dereferences the resulting pointer, and assigns 6 to it.


    If "array" implicitly converted to: int (*)[5]
    rather than a pointer to the first element, then Step 2 above would be
    different, specifically:


    2) Adds 3 * sizeof( int[5] ) to the address.


    And we know that sizeof(int[5]) is 20 on this platform (not 8!).


    So you may ask, "What's the point in having a pointer to an array?" -- well
    here's where it may come in handy:


    void SomeFunc ( int (* const p_array)[5] )
    {
    (*p_array)[0] = 99;
    (*p_array)[1] = 98;
    (*p_array)[2] = 97;
    (*p_array)[3] = 96;
    (*p_array)[4] = 95;

    /* This function won't accept an array of any
    other size! */
    }


    And here's a C++-specific example with references:

    void SomeFunc ( int (&array)[5] )
    {
    array[0] = 99;
    array[1] = 98;
    array[2] = 97;
    array[3] = 96;
    array[4] = 95;

    /* This function won't accept an array of any
    other size! */
    }


    Also in C++, you can exploit the use of templates:

    template<class T, unsigned long len>
    void KeepCopy( const T (&array)[len] )
    {
    static my_array[len];

    /* Do some other stuff */
    }


    I've posted this to a few newsgroups, so if you'd like to reply, please post
    to comp.lang.c because it's the common denominator. If your post is C++-
    specific, the please post to comp.lang.c++.

    Did I leave anything out?

    -Tomás

    [ See http://www.gotw.ca/resources/clcm.htm for info about ]
    [ comp.lang.c++.moderated. First time posters: Do this! ]
    --
    comp.lang.c.moderated - moderation address: -- you must
    have an appropriate newsgroups line in your header for your mail to be seen,
    or the newsgroup name in square brackets in the subject line. Sorry.
     
    Tomás, May 11, 2006
    #1
    1. Advertising

  2. Tomás

    Richard Bos Guest

    "Tomás" <> wrote:

    > Some programmers treat arrays just like pointers (and some even think that
    > they're exactly equivalent). I'm going to demonstrate the differences.
    >
    > Firstly, let's assume that we're working on a platform which has the
    > following properties:
    >
    > 1) char's are 8-Bit. ( "char" is synomonous with "byte" ).


    A char is _always_ a byte. What you mean is that you are assuming a char
    (and therefore also a byte) to be equal to an octet.

    > 2) int's are 32-Bit. ( sizeof(int) == 4 ).
    > 3) Pointers are 64-Bit. ( sizeof(int*) == 8 ).



    > First let's make two declarations:
    >
    > int main(void)
    > {
    > int array[5];
    >
    > int* const pointer = (int*)malloc( 5 * sizeof(int) );


    *Boing* and here the demonstration crashes.

    Never cast malloc(). It is not necessary. void *s can be freely
    converted to and from any object pointer type.
    Never use malloc() (or any other function, for that matter) without a
    proper declaration in scope. It forces your compiler to assume that the
    function returns an int, which malloc() clearly does not.

    Note that the first error hides the second. The combination of the two
    can result in garbage being assigned to your pointer.

    As a matter of convenient maintenance, not a true error, it is more
    dabble-proof to use sizeof *pointer rather than sizeof (type). If your
    pointer's type changes, the first form stays correct, the second can
    turn deceptively (and hiddenly!) broken.

    All in all, that program should've looked like this:

    #include <stdlib.h>

    int main(void)
    {
    int array[5];

    int* const pointer = malloc(5 * sizeof *pointer);
    }

    Anyway, the difference between pointers and arrays is most simply
    demonstrated using the age[1]-old method of arrows and groups of boxes.

    Richard

    [1] I.e., in the computing world, a couple of decades
     
    Richard Bos, May 11, 2006
    #2
    1. Advertising

  3. Tomás wrote:

    > Some programmers treat arrays just like pointers (and some even think that
    > they're exactly equivalent). I'm going to demonstrate the differences.


    Some of these days you can also write an article demonstrating that integer
    types are not floating point types. It will be another great contribution
    to the progress of humanity.

    --
    Salu2

    Inviato da X-Privat.Org - Registrazione gratuita http://www.x-privat.org/join.php
     
    =?ISO-8859-15?Q?Juli=E1n?= Albo, May 11, 2006
    #3
  4. Tomás

    Chad Guest


    > As a matter of convenient maintenance, not a true error, it is more
    > dabble-proof to use sizeof *pointer rather than sizeof (type). If your
    > pointer's type changes, the first form stays correct, the second can
    > turn deceptively (and hiddenly!) broken.
    >
    > All in all, that program should've looked like this:
    >
    > #include <stdlib.h>
    >
    > int main(void)
    > {
    > int array[5];
    >
    > int* const pointer = malloc(5 * sizeof *pointer);
    > }
    >
    > Anyway, the difference between pointers and arrays is most simply
    > demonstrated using the age[1]-old method of arrows and groups of boxes.
    >
    > Richard
    >
    > [1] I.e., in the computing world, a couple of decades


    Okay, I'm probably missing this. But say I have the following:

    /*I omitted checking for NULL and using free*/

    #include <stdio.h>
    #include <stdlib.h>

    int main(void) {
    int array[5];

    int *q = malloc(sizeof *array);

    return 0;
    }


    Now, I change
    int array[5];

    to

    double array[5];

    Wouldn't the sizeof double be truncated to the sizeof int? If so, the
    wouldn't this create an additional bug?

    Chad
     
    Chad, May 11, 2006
    #4
  5. Tomás

    CBFalconer Guest

    Chad wrote:
    >

    .... snip ...
    >
    > Okay, I'm probably missing this. But say I have the following:
    >
    > /*I omitted checking for NULL and using free*/
    >
    > #include <stdio.h>
    > #include <stdlib.h>
    >
    > int main(void) {
    > int array[5];
    >
    > int *q = malloc(sizeof *array);


    There is no such thing as *array. array is an array of 5 integers,
    not a pointer.

    --
    Some informative links:
    news:news.announce.newusers
    http://www.geocities.com/nnqweb/
    http://www.catb.org/~esr/faqs/smart-questions.html
    http://www.caliburn.nl/topposting.html
    http://www.netmeister.org/news/learn2quote.html
     
    CBFalconer, May 11, 2006
    #5
  6. Tomás

    Flash Gordon Guest

    Chad wrote:
    >> As a matter of convenient maintenance, not a true error, it is more
    >> dabble-proof to use sizeof *pointer rather than sizeof (type). If your
    >> pointer's type changes, the first form stays correct, the second can
    >> turn deceptively (and hiddenly!) broken.
    >>
    >> All in all, that program should've looked like this:
    >>
    >> #include <stdlib.h>
    >>
    >> int main(void)
    >> {
    >> int array[5];
    >>
    >> int* const pointer = malloc(5 * sizeof *pointer);
    >> }
    >>
    >> Anyway, the difference between pointers and arrays is most simply
    >> demonstrated using the age[1]-old method of arrows and groups of boxes.
    >>
    >> Richard
    >>
    >> [1] I.e., in the computing world, a couple of decades

    >
    > Okay, I'm probably missing this. But say I have the following:
    >
    > /*I omitted checking for NULL and using free*/
    >
    > #include <stdio.h>
    > #include <stdlib.h>
    >
    > int main(void) {
    > int array[5];
    >
    > int *q = malloc(sizeof *array);
    >
    > return 0;
    > }
    >
    >
    > Now, I change
    > int array[5];
    >
    > to
    >
    > double array[5];
    >
    > Wouldn't the sizeof double be truncated to the sizeof int? If so, the
    > wouldn't this create an additional bug?


    You have not followed the suggested practice of using sizeof *pointer
    being assigned to. Your example should have been:
    #include <stdlib.h>

    int main(void) {
    int array[5];

    int *q = malloc(sizeof *q);

    return 0;
    }

    Or, if you want array and q to always be the same type, you could have used:
    #include <stdlib.h>
    int main(void) {
    int array[5], *q = malloc(sizeof *q);

    return 0;
    }

    I really can't see why you would think of using sizeof some other object.
    --
    Flash Gordon, living in interesting times.
    Web site - http://home.flash-gordon.me.uk/
    comp.lang.c posting guidelines and intro:
    http://clc-wiki.net/wiki/Intro_to_clc

    Inviato da X-Privat.Org - Registrazione gratuita http://www.x-privat.org/join.php
     
    Flash Gordon, May 11, 2006
    #6
  7. CBFalconer wrote:
    >
    > Chad wrote:
    > >

    > ... snip ...
    > >
    > > Okay, I'm probably missing this. But say I have the following:
    > >
    > > /*I omitted checking for NULL and using free*/
    > >
    > > #include <stdio.h>
    > > #include <stdlib.h>
    > >
    > > int main(void) {
    > > int array[5];
    > >
    > > int *q = malloc(sizeof *array);

    >
    > There is no such thing as *array. array is an array of 5 integers,
    > not a pointer.
    >

    "array[0]" is the same as "*(array+0)" which simplifies to "*array".


    --
    +----------------------------------------------------------------+
    | Charles and Francis Richmond richmond at plano dot net |
    +----------------------------------------------------------------+
     
    Charles Richmond, May 11, 2006
    #7
  8. Tomás

    CBFalconer Guest

    Charles Richmond wrote:
    > CBFalconer wrote:
    >> Chad wrote:
    >> >

    >> ... snip ...
    >>>
    >>> Okay, I'm probably missing this. But say I have the following:
    >>>
    >>> /*I omitted checking for NULL and using free*/
    >>>
    >>> #include <stdio.h>
    >>> #include <stdlib.h>
    >>>
    >>> int main(void) {
    >>> int array[5];
    >>>
    >>> int *q = malloc(sizeof *array);

    >>
    >> There is no such thing as *array. array is an array of 5 integers,
    >> not a pointer.

    >
    > "array[0]" is the same as "*(array+0)" which simplifies to "*array".


    When array is passed as a parameter, which this one isn't.

    --
    Some informative links:
    news:news.announce.newusers
    http://www.geocities.com/nnqweb/
    http://www.catb.org/~esr/faqs/smart-questions.html
    http://www.caliburn.nl/topposting.html
    http://www.netmeister.org/news/learn2quote.html
     
    CBFalconer, May 11, 2006
    #8
  9. Tomás

    pete Guest

    CBFalconer wrote:
    >
    > Chad wrote:


    > > int array[5];
    > >
    > > int *q = malloc(sizeof *array);

    >
    > There is no such thing as *array. array is an array of 5 integers,
    > not a pointer.


    (*array) is an expression of type int.

    The operand of sizeof is (*array), not (array),
    so, array gets converted to a pointer.

    --
    pete
     
    pete, May 12, 2006
    #9
  10. Tomás

    Tomás Guest

    CBFalconer posted:


    >> "array[0]" is the same as "*(array+0)" which simplifies to "*array".

    >
    > When array is passed as a parameter, which this one isn't.



    Stop trolling and propogating misinformation.

    "array" implicitly converts to a pointer to its first element ALL THE TIME
    -- NOT just when passed as an argument to a function, NOT just when it's a
    global variable, NOT just when you have porridge instead of cereal.

    -Tomás
     
    Tomás, May 12, 2006
    #10
  11. Tomás

    Nelu Guest

    Tomás wrote:
    > CBFalconer posted:
    >
    >
    > >> "array[0]" is the same as "*(array+0)" which simplifies to "*array".

    > >
    > > When array is passed as a parameter, which this one isn't.

    >
    >
    > Stop trolling and propogating misinformation.
    >
    > "array" implicitly converts to a pointer to its first element ALL THE TIME
    > -- NOT just when passed as an argument to a function, NOT just when it's a
    > global variable, NOT just when you have porridge instead of cereal.


    I keep trying to compile the following program:

    void f(char *b) {
    b++;
    }

    int main(void) {
    char a[]={'a','b','c'};

    a++;

    f(a);

    return 0;
    }

    Let me know where it fails on your C compiler as a should implicitly
    convert to a pointer, right?

    --
    Ioan - Ciprian Tandau
    tandau _at_ freeshell _dot_ org (hope it's not too late)
    (... and that it still works...)
     
    Nelu, May 12, 2006
    #11
  12. Tomás

    pete Guest

    Nelu wrote:
    >
    > Tomás wrote:
    > > CBFalconer posted:
    > >
    > >
    > > >> "array[0]" is the same as "*(array+0)"
    > > >> which simplifies to "*array".
    > > >
    > > > When array is passed as a parameter, which this one isn't.

    > >
    > >
    > > Stop trolling and propogating misinformation.
    > >
    > > "array" implicitly converts to a pointer to its first element
    > > ALL THE TIME
    > > -- NOT just when passed as an argument to a function,
    > > NOT just when it's a
    > > global variable, NOT just when you have porridge instead of cereal.


    Stop trolling and propogating misinformation.

    An expression of array type is not coverted
    when it is the operand of the sizeof operator.
    An expression of array type is not coverted
    when it is the operand of the address operator.

    > I keep trying to compile the following program:


    > int main(void) {
    > char a[]={'a','b','c'};
    >
    > a++;


    > Let me know where it fails on your C compiler as a should implicitly
    > convert to a pointer, right?


    "(8) : error C2105: '++' needs l-value"

    One problem with (a++),
    is that the result of a type conversion is not an lvalue.

    N869
    6.3.2 Other operands
    6.3.2.1 Lvalues and function designators

    [#3] Except when it is the operand of the sizeof operator or
    the unary & operator, or is a string literal used to
    initialize an array, an expression that has type ``array of
    type'' is converted to an expression with type ``pointer to
    type'' that points to the initial element of the array
    object and is not an lvalue. If the array object has
    register storage class, the behavior is undefined.

    --
    pete
     
    pete, May 12, 2006
    #12
  13. Tomás

    Nelu Guest

    pete wrote:
    > Nelu wrote:
    > >
    > > Tomás wrote:
    > > > CBFalconer posted:
    > > >
    > > >
    > > > >> "array[0]" is the same as "*(array+0)"
    > > > >> which simplifies to "*array".
    > > > >
    > > > > When array is passed as a parameter, which this one isn't.
    > > >
    > > >
    > > > Stop trolling and propogating misinformation.
    > > >
    > > > "array" implicitly converts to a pointer to its first element
    > > > ALL THE TIME
    > > > -- NOT just when passed as an argument to a function,
    > > > NOT just when it's a
    > > > global variable, NOT just when you have porridge instead of cereal.

    >
    > Stop trolling and propogating misinformation.
    >
    > An expression of array type is not coverted
    > when it is the operand of the sizeof operator.
    > An expression of array type is not coverted
    > when it is the operand of the address operator.
    >
    > > I keep trying to compile the following program:

    >
    > > int main(void) {
    > > char a[]={'a','b','c'};
    > >
    > > a++;

    >
    > > Let me know where it fails on your C compiler as a should implicitly
    > > convert to a pointer, right?

    >
    > "(8) : error C2105: '++' needs l-value"
    >
    > One problem with (a++),
    > is that the result of a type conversion is not an lvalue.
    >
    > N869
    > 6.3.2 Other operands
    > 6.3.2.1 Lvalues and function designators
    >
    > [#3] Except when it is the operand of the sizeof operator or
    > the unary & operator, or is a string literal used to
    > initialize an array, an expression that has type ``array of
    > type'' is converted to an expression with type ``pointer to
    > type'' that points to the initial element of the array
    > object and is not an lvalue. If the array object has
    > register storage class, the behavior is undefined.
    >


    If it's not an lvalue doesn't it mean that it's not a pointer *object*
    but a pointer value?

    --
    Ioan - Ciprian Tandau
    tandau _at_ freeshell _dot_ org (hope it's not too late)
    (... and that it still works...)
     
    Nelu, May 12, 2006
    #13
  14. Tomás

    Tomás Guest


    > If it's not an lvalue doesn't it mean that it's not a pointer *object*
    > but a pointer value?



    From the Standard:

    An lvalue refers to an object or function. Some rvalue expressions —-
    those of class or cv-qualified class type -- also refer to objects.


    -Tomás
     
    Tomás, May 12, 2006
    #14
  15. Tomás

    pete Guest

    Nelu wrote:
    >
    > pete wrote:
    > > Nelu wrote:
    > > >
    > > > Tomás wrote:
    > > > > CBFalconer posted:
    > > > >
    > > > >
    > > > > >> "array[0]" is the same as "*(array+0)"
    > > > > >> which simplifies to "*array".
    > > > > >
    > > > > > When array is passed as a parameter, which this one isn't.
    > > > >
    > > > >
    > > > > Stop trolling and propogating misinformation.
    > > > >
    > > > > "array" implicitly converts to a pointer to its first element
    > > > > ALL THE TIME
    > > > > -- NOT just when passed as an argument to a function,
    > > > > NOT just when it's a
    > > > > global variable, NOT just when you have porridge instead of cereal.

    > >
    > > Stop trolling and propogating misinformation.
    > >
    > > An expression of array type is not coverted
    > > when it is the operand of the sizeof operator.
    > > An expression of array type is not coverted
    > > when it is the operand of the address operator.
    > >
    > > > I keep trying to compile the following program:

    > >
    > > > int main(void) {
    > > > char a[]={'a','b','c'};
    > > >
    > > > a++;

    > >
    > > > Let me know where it fails on your C compiler
    > > > as a should implicitly
    > > > convert to a pointer, right?

    > >
    > > "(8) : error C2105: '++' needs l-value"
    > >
    > > One problem with (a++),
    > > is that the result of a type conversion is not an lvalue.
    > >
    > > N869
    > > 6.3.2 Other operands
    > > 6.3.2.1 Lvalues and function designators
    > >
    > > [#3] Except when it is the operand of the sizeof operator or
    > > the unary & operator, or is a string literal used to
    > > initialize an array, an expression that has type ``array of
    > > type'' is converted to an expression with type ``pointer to
    > > type'' that points to the initial element of the array
    > > object and is not an lvalue. If the array object has
    > > register storage class, the behavior is undefined.
    > >

    >
    > If it's not an lvalue doesn't it mean that it's not a pointer *object*
    > but a pointer value?


    Yes.

    (a++) means the same thing as ((a + 0)++)

    --
    pete
     
    pete, May 12, 2006
    #15
  16. Tomás

    pete Guest

    Tomás wrote:

    > Some rvalue expressions —-
    > those of class or cv-qualified class type -- also refer to objects.


    What does "class or cv-qualified class type" mean?

    Is that C++?

    --
    pete
     
    pete, May 12, 2006
    #16
  17. Tomás

    Chad Guest


    > You have not followed the suggested practice of using sizeof *pointer
    > being assigned to. Your example should have been:
    > #include <stdlib.h>
    >
    > int main(void) {
    > int array[5];
    >
    > int *q = malloc(sizeof *q);
    >
    > return 0;
    > }
    >
    > Or, if you want array and q to always be the same type, you could have used:
    > #include <stdlib.h>
    > int main(void) {
    > int array[5], *q = malloc(sizeof *q);
    >
    > return 0;
    > }
    >
    > I really can't see why you would think of using sizeof some other object.
    > --
    > Flash Gordon, living in interesting times.
    > Web site - http://home.flash-gordon.me.uk/
    > comp.lang.c posting guidelines and intro:
    > http://clc-wiki.net/wiki/Intro_to_clc
    >
    > Inviato da X-Privat.Org - Registrazione gratuita http://www.x-privat.org/join.php


    I can't really put me pinpoint the exact part, but I know I'm missing
    some kind of underlying concept when I see the construction:

    int *q = malloc(sizeof *q);

    Maybe when I'm scrubbing the dairy coolers at work tomorrow morning,
    the exact part that is irking me will set in. Then I can come back and
    ask the EXACT question about the construction.

    Chad
     
    Chad, May 12, 2006
    #17
  18. Chad said:
    >
    > I can't really put me pinpoint the exact part, but I know I'm missing
    > some kind of underlying concept when I see the construction:
    >
    > int *q = malloc(sizeof *q);


    The canonical way to allocate space for n objects of type T is:

    T *p = malloc(n * sizeof *p);

    or, if p is already declared, simply this:

    p = malloc(n * sizeof *p);

    The reason this is the canonical way is that it doesn't rely on the type of
    p, except that it must be an object type, not an incomplete type or
    function type. If the type of p changes during maintenance, you don't have
    to hunt down this line and hack it about. It will automagically work
    correctly with the new type.

    --
    Richard Heathfield
    "Usenet is a strange place" - dmr 29/7/1999
    http://www.cpax.org.uk
    email: rjh at above domain (but drop the www, obviously)
     
    Richard Heathfield, May 12, 2006
    #18
  19. Tomás

    Jack Klein Guest

    On Thu, 11 May 2006 11:25:49 -0400, CBFalconer <>
    wrote in comp.lang.c:

    > Chad wrote:
    > >

    > ... snip ...
    > >
    > > Okay, I'm probably missing this. But say I have the following:
    > >
    > > /*I omitted checking for NULL and using free*/
    > >
    > > #include <stdio.h>
    > > #include <stdlib.h>
    > >
    > > int main(void) {
    > > int array[5];
    > >
    > > int *q = malloc(sizeof *array);

    >
    > There is no such thing as *array. array is an array of 5 integers,
    > not a pointer.


    I beg your pardon. There most definitely is such a thing as *array,
    because of the implicit and automatic conversion of the name of an
    array to a pointer in all expressions other than unary & and sizeof.

    Compile and execute yourself:

    #include <stdio.h>

    int main(void)
    {
    double array1 [10];
    char array2 [10];

    printf("sizeof *array1 = %d\n", (int)sizeof *array1);
    printf("sizeof *array2 = %d\n", (int)sizeof *array2);

    return 0;
    }

    I get:

    sizeof *array1 = 8
    sizeof *array2 = 1
    --
    Jack Klein
    Home: http://JK-Technology.Com
    FAQs for
    comp.lang.c http://c-faq.com/
    comp.lang.c++ http://www.parashift.com/c -faq-lite/
    alt.comp.lang.learn.c-c++
    http://www.contrib.andrew.cmu.edu/~ajo/docs/FAQ-acllc.html
     
    Jack Klein, May 12, 2006
    #19
  20. Tomás

    Chad Guest

    Richard Heathfield wrote:
    > Chad said:
    > >
    > > I can't really put me pinpoint the exact part, but I know I'm missing
    > > some kind of underlying concept when I see the construction:
    > >
    > > int *q = malloc(sizeof *q);

    >
    > The canonical way to allocate space for n objects of type T is:
    >
    > T *p = malloc(n * sizeof *p);
    >
    > or, if p is already declared, simply this:
    >
    > p = malloc(n * sizeof *p);
    >
    > The reason this is the canonical way is that it doesn't rely on the type of
    > p, except that it must be an object type, not an incomplete type or
    > function type. If the type of p changes during maintenance, you don't have
    > to hunt down this line and hack it about. It will automagically work
    > correctly with the new type.
    >
    > --
    > Richard Heathfield
    > "Usenet is a strange place" - dmr 29/7/1999
    > http://www.cpax.org.uk
    > email: rjh at above domain (but drop the www, obviously)


    Hmmm... It looks like got a response before I could correct the grammar
    errors in my previous post. Anyhow, I think I managed to pinpoint what
    is irking me.

    Say I have the following:

    /*I omitted checking malloc() for NULL and forgot to use free()*/
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    int main(void) {
    char *p = malloc(sizeof *p);
    /* incomplete -- malloc's return value not checked */
    strcpy(p, "Hello, world!");

    return 0;
    }

    Are you saying that the construction
    char *p = malloc(sizeof *p);

    would allocate enough space to hold the string ""Hello, world!" versus
    allocating memory to hold just one char?

    Chad
     
    Chad, May 12, 2006
    #20
    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. sangeetha

    Array of pointer Vs Pointer to Array

    sangeetha, Oct 8, 2004, in forum: C Programming
    Replies:
    9
    Views:
    352
    Tim Rentsch
    Oct 9, 2004
  2. Tomás

    Array and Pointer Tutorial

    Tomás, May 11, 2006, in forum: C++
    Replies:
    1
    Views:
    397
    =?ISO-8859-15?Q?Juli=E1n?= Albo
    May 11, 2006
  3. erfan

    Array of pointer and pointer of array

    erfan, Jan 28, 2008, in forum: C Programming
    Replies:
    6
    Views:
    678
    Martin Ambuhl
    Jan 28, 2008
  4. RSL
    Replies:
    14
    Views:
    3,270
  5. , India

    pointer to an array vs pointer to pointer

    , India, Sep 20, 2011, in forum: C Programming
    Replies:
    5
    Views:
    460
    James Kuyper
    Sep 23, 2011
Loading...

Share This Page