Thread: pointer vs array...

  1. #1
    Registered User
    Join Date
    Jul 2012
    Posts
    36

    pointer vs array...

    Code:
    char a[] = "Tennisstar"; // this works
    char *a = "Tennisstar"; // this also works
    
    /*but a pointer is a variable that stores a mem. add. and an array is a
    group of varibles... how how are they same?
    Why doesn't it work with integers?
    Why in int arrays you have to specify a number between the square brackets (size) but not in char?*/
    
    /*and yes... all nerds out there
    please explain in simple terms since i am a beginner...
    THANX!!!*/

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    You mean this doesn't work?
    Code:
    int array[] = { 1, 2, 3, 4 };
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Quote Originally Posted by tennisstar View Post
    [how are they same?
    They are not the same.When you have a array ,you can not move the pointer ,which points to the array, but you can modify the contents.When you have a char pointer, you can not modify the content , but you can move the pointer.
    Example
    Code:
    #include <iostream>
    
    
    using namespace std;
    int main()
    {
        char a[] = "Tennisstar";
        char *b = "Tennisstar";
        char *c = "SAMARAS";
    
        a[6]='W';
    
        b = c;
    
        b[6] = 'W'; /* Error */
    
        a = c;   /* Error */
    
        cout<<"a is "<<a<<endl;
        cout<<"b is "<<b<<endl;
        cout<<"c is "<<c<<endl;
    
        return 0;
    }

    Quote Originally Posted by tennisstar View Post
    /*and yes... all nerds out there
    please explain in simple terms since i am a beginner...*/
    ...


    PS - Learn how to use string.If you posted in the right thread and you want to learn C++.

  4. #4
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Quote Originally Posted by std10093 View Post
    They are not the same.When you have a array ,you can not move the pointer ,which points to the array, but you can modify the contents.
    This explanation is kind of poor. Array types are not pointer types, so it is best to avoid explaining them with the word pointer. In fact, if you use the word pointer you probably failed.

    Array types are collections of variables. They are not l-values themselves. If you try to use an array in an l-value context, this will be apparent because there is nowhere to store any relevant changes.

    Code:
    int main()
    {
    int bar[4];
    int array[4];
    array = bar;
    ++array;
    array -= 2;
    return 0;
    }
    
    #if 0
    In function 'main':
    Line 5: error: incompatible types in assignment
    Line 6: error: invalid lvalue in increment
    Line 7: error: invalid operands to binary -
    #endif
    The "arrays decay to pointer to the first element" rule pretty much dominate the acceptable uses, except when you use sizeof, &, or a string literal used to initialize an array.

  5. #5
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    whiteflags, yes i agree that i could explain it better.
    But remember that
    Code:
    int v[5];
    v is a pointer to first element of array

  6. #6
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    The compiler disagrees with you. The type of v is in fact int[5] unless you use it in a pointer context.

  7. #7
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by std10093 View Post
    But remember that
    Code:
    int v[5];
    v is a pointer to first element of array
    No, it is not. As whiteflags said, v is an array of 5 ints.

    Names of arrays can be treated as if they are pointers, in some contexts. That does not mean an array is a pointer. There are contexts where the difference is readily apparent.

    If you look through this forum (and any other forum concerned with C or C++) you will find numerous questions asked because folks have incorrectly believed that arrays are pointers, only to experience surprising (to them) effects caused by the fact that pointers and arrays are distinct things.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  8. #8
    Dweeb dojha00's Avatar
    Join Date
    Feb 2012
    Location
    Global
    Posts
    23
    I think this example will make clear the difference between a pointer and an array..
    Code:
    char charr[]="This";
    char *chptr="This";
    printf("%u",&charr);//This will print starting address of string "This". charr takes no space to get store.
    printf("%u",&chptr);// This will print the address of pointer chptr while this is not starting from there and it's taking space 4byte in gcc to store address..

  9. #9
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Not true, doha.

    Firstly, printing out addresses using the %u format causes undefined behaviour.

    Second (even tying on the blindfolds and ignoring the undefined behaviour) your comments do not really reflect what is happening.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  10. #10
    Registered User
    Join Date
    Jul 2012
    Posts
    36

    I don't mean that...

    See... char[] works because it is an array of char variables but how can char* work because it is not an array of chars but it is a pointer which can store the memory address of a variable with the datatype char... that is what i wanted to know...

    and yes.. by "Why doesn't it work for int?" i meant why cant you do int* a = 1213 like that... and why can you do it to char like char* a = "tennisstar"

    thanx in advance...

  11. #11
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Since you are confused about how pointers can point to strings I recommend reading:
    Question 1.32

    I take it for granted that why people choose to use pointers to strings instead of making arrays is less confusing to you. A lot of the reason for using pointers to strings comes from planning ahead: if you aren't going to be editing a debugging string, then there is little sense in using arrays which are editable when there is a more restrictive choice available in pointers.

    i meant why cant you do int* a = 1213
    That does have a meaning. Well, it did, but C++ explicitly disallows it. Initializing/Assigning an integer to a pointer would change its value in the C language.

    But let's go deeper. As for why you can point pointers at strings and not do the same for integer arrays, well it just takes a bit of thinking. With strings it should be obvious that each letter maps to a location, or group of locations, as Unicode encodings may force you to do, in a string. Programming languages are human inventions and we are used to communicating in text within everyday life. Applying this experience to numbers is significantly harder. 1213 in that context could mean this or a number of other combos:
    Code:
    int *a = { 1, 2, 1, 3 };
    or
    int *a = {12, 13};
    or even
    int *a = {1213};
    If the compiler is going to work, it has to know what your intention is for the array that is being assigned. And that's pretty much all I can say on the topic. It took a few edits to get there.
    Last edited by whiteflags; 11-10-2012 at 01:27 AM.

  12. #12
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by tennisstar View Post
    and yes.. by "Why doesn't it work for int?" i meant why cant you do int* a = 1213 like that... and why can you do it to char like char* a = "tennisstar"
    Ah. You're asking about the infamous anomaly of C.

    Firstly, it doesn't make sense to do "int *a = 1213" any more than it makes sense to do "char *c = ' '" (note the single quotes in the char example). Both are invalid, and will cause a compiler to complain, for the same reason. It makes no sense to convert an int value (1213) into a pointer, and also makes no sense to convert a char value (' ', which is 32 with the ASCII character set) into a pointer.


    But, to come to your question, the handling of char strings to initialise char pointers is actually a historical anomaly in the language. Originally, in early versions of C (I'm not sure if this predated K&R C, or was originally part of K&R C) it was never valid to initialise a pointer using an array.

    At that time, these constructs were valid
    Code:
        int ai[] = {1,2,3};
        int *pi = i;               /*   equivalent to   int *pi = &ai[0] */
    
        char ac[] = "xy";        /*   equivalent to  char ac[] = {'x', 'y', '\0'}  */
        char *pc = c;
    but these constructs were not valid
    Code:
        int *pi = {1,2,3};
        char *pc = "xy";
    This is how it was, and compilers were shipped. Programmers, if they wanted a pointer that was initialised so it contained the first address of a char literal, were forced to do
    Code:
        char *ac[] = "xy";
        char *pc = ac;
    
          /*   code that uses pc but never again references ac */
    A few too many programmers at the time were zealots of terse code, so they thought it made sense to do
    Code:
        char *pc = "xy";
    
          /*   code that uses pc */
    and their compilers complained bitterly about this. Those programmers then lobbied their compiler vendors to allow this to happen. However, the same programmers caused some bemusement for their compiler vendors by insisting that
    Code:
        int *pi = {1,2,3};
    should still be invalid.

    Hence, today, we have an anomaly in the C language. Character pointers can be initialised directly using a string literal, but pointers to other types cannot be initialised using an array initialiser.

    The reason for this anomaly is purely non-technical. In fact, it was quite political, and the arguments in favour of the anomaly often amounted to religious fervour (from those who worship at the altar of terseness).
    Last edited by grumpy; 11-10-2012 at 01:32 AM.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  13. #13
    Registered User
    Join Date
    Jul 2012
    Posts
    36
    Hey all...
    its me tennisstar...

    while i was programming today... i came up to this assumption...
    (note: this is just an assumption and i just wanna figure out if i was right...)

    Code:
    //when i do:
    char a[11] = "Tennisstar"; // the extra 1 for the /0 character
    // it works because a is an array of chars....
    char *b = "Tennisstar";
    // also works and i'm trying to figure out how
    char *c = new char[256]
    //works because it points to an array of chars...
    
    /*So my assumption is that when you create a char* and assign it a value like "Tennisstar" it assumes that
     your pointer points to an array of chars*/
    /*I just wanna know if i'm right or wrong
    if right i'll relax
    if wrong i'll continue the hunt for my answer
    */
    //THANKYOU everyone in advance
    Last edited by tennisstar; 11-10-2012 at 07:25 AM.

  14. #14
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    /*So my assumption is that when you create a char* and assign it a value like "Tennisstar" it assumes that
    your pointer points to an array of chars*/
    Pretty much.

  15. #15
    Dweeb dojha00's Avatar
    Join Date
    Feb 2012
    Location
    Global
    Posts
    23
    Quote Originally Posted by grumpy View Post
    Not true, doha.

    Firstly, printing out addresses using the %u format causes undefined behaviour.
    I used %u so it's easy to manipulate.
    Can u please explain the meaning of "undefined behaviour"?
    Second (even tying on the blindfolds and ignoring the undefined behaviour) your comments do not really reflect what is happening.
    Let me make clear what i m trying to say in comments:
    1. This printf statement will print the address of char 'T' of string "This" and variable 'charr' will be stored in symbol table to link it when variable is used.
    2. In this when chptr will be used it will bind the address where address of string "this" is stored. and chptr will take 4 byte to store the starting address of "this".

    Now if still it's wrong then make me correct..
    What is life??

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 01-28-2010, 02:44 AM
  2. Casting from a 1D array pointer to a scalar pointer
    By komkamol in forum C Programming
    Replies: 8
    Last Post: 09-25-2009, 01:44 AM
  3. pointer to pointer that points to a char array
    By steve1_rm in forum C Programming
    Replies: 2
    Last Post: 01-14-2009, 12:03 AM
  4. Replies: 1
    Last Post: 03-24-2008, 10:16 AM
  5. A pointer to a character pointer array... can't pass
    By Lynux-Penguin in forum C Programming
    Replies: 9
    Last Post: 10-12-2003, 10:53 PM