Thread: Question on char arrays

  1. #1
    C/C++ homeyg's Avatar
    Join Date
    Nov 2004
    Location
    Louisiana, USA
    Posts
    209

    Question on char arrays

    In the book in my avatar (this has become my new catch frase), I came across a few things in the section on pointers which they do not clearly explain. Here's an example:
    Code:
    char* szString = "Randy";
    I see that this is an array of characters, but why is it declared like a pointer? I don't understand how this works. Here's the full example from the book:
    Code:
    // DisplayString - display an array of characters both
    //                 using a pointer and an array index
    #include <cstdio>
    #include <cstdlib>
    #include <iostream>
    using namespace std;
    
    int main(int nNumberofArgs, char* pszArgs[])
    {
        // declare a string
        char* szString = "Randy";
        cout << "The array is '" << szString << "'" << endl;
        
        // display szString as an array
        cout << "Display the string as an array: ";
        for(int i = 0; i < 5; i++)
        {
          cout << szString[i];
        }
        cout << endl;
        
        // now using typical pointer arithmetic
        cout << "Display string using a pointer: ";
        char* pszString = szString;
        while(*pszString)
        {
          cout << *pszString;
          pszString++;
        }
        cout << endl;
    
        // wait until user is ready before terminating program
        // to allow the user to see the program results
        system("PAUSE");
        return 0; 
    }

  2. #2
    Registered User
    Join Date
    Dec 2004
    Location
    UK
    Posts
    109
    In c/c++ an array IS a pointer. They are equivalent in everything (except I believe the c++ compiler will I am sillyI am sillyI am sillyI am sillyI am silly if you mix them up in some situations)

    Possibly someone else will be able to give a more detailed explanation.

  3. #3
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    "Randy" is a string literal that is stored in an area (data segment?) of the program at a particular address. szString is a pointer that gets initialized to this address.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  4. #4
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    In c/c++ an array IS a pointer.
    What?

  5. #5
    Quote Originally Posted by sigfriedmcwild
    In c/c++ an array IS a pointer.
    » I beg to differ. There is a strong relationship between pointers and arrays. Any operation that can be acheived by array subscripting can also be done with pointers. The pointer version will in general be faster but, at least to the uninitiated, somewhat harder to understand.
    Quote Originally Posted by homeyg
    I see that this is an array of characters, but why is it declared like a pointer?
    » What you have there is a string literal. szString is a pointer that is initialized to contain the read-only address of a string constant; the pointer may subsequently be modified to point elsewhere, but the result is undefined if you attempt to modify the strings contents.


    - Stack Overflow
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  6. #6
    Magically delicious LuckY's Avatar
    Join Date
    Oct 2001
    Posts
    856
    Any variable name by which you can refer to an array is, in actuality, a pointer containing the starting address of the array. Let's consider the following example:
    Code:
    char buffer[10];
    Your program will create 10 consecutive bytes in memory somewhere for buffer to access and buffer itself will also have a 4-byte (generally) piece of memory somewhere else. buffer is a pointer, so it's location in memory will contain the address of the first of those ten bytes. This is why if you wanted to set/check the first byte in your array, for example, you would dereference it like so (instructing the compiler to go to the address contained in buffer, then assign the byte in that location the value 'X'):
    Code:
    *buffer = 'X';
    Now, back to your original question. At compile time, in the part of your program's memory where constants are stored, six bytes are created: 'R', 'a', 'n', 'd', 'y', '\0'. So at any point in your program where you might do something like
    Code:
    char *szString = "Randy";
    szString (which is a 4-byte pointer) will just be set to the address of the first byte in that 6-byte array. (Side note: depending on your compiler/settings multiple references to a duplicate constant may or may not have a single occurrence in memory).

    So, to simplify the explanation, any array of data may only be accessed using a pointer (which is what I believe sigfriedmchammer was attempting to say). This is not concordant with the general statement that a pointer may access any array, however. In my example, buffer could not be made to point at another location. E.g., the following would not compile:
    Code:
    buffer = "Randy";
    Although, you may further note that the following will compile as it simply instructs the compiler to initialize the array:
    Code:
    char buffer[10] = "Randy";
    Last edited by LuckY; 12-21-2004 at 05:15 PM. Reason: Grammatical syntax error

  7. #7
    Hardware Engineer
    Join Date
    Sep 2001
    Posts
    1,398
    1. Pointers are used for character arrays because in C++ a single variable only "holds" one value (i.e. one character). That is, you can't use a single variable name to represent a whole array of characters.

    However, you can use a single variable name to represent a pointer to the first character in the array. And, arrays are stored sequentially in memory, so you can get-to the whole array this way.

    2. This may be confusing: C++ automatically treats the non-subscripted array-name as a pointer, and vice-versa. So when you use the C-string manipulation functions from <cstring>, you use a variable like szString, which is a pointer even if you didn't declare it as a pointer. ...You might not realize that you are using a pointer! Or, you can access one character in the array with szString[n], even though you didn't declare szString as an array.

    Here's what I'm trying to say:
    Code:
    char* szString = "Randy";
        //szString is a pointer to the 'R'  (The first character of the array)
        //szString[0] = 'R' (automatically)
    
    
    // Or, 
    char szString[] = "Randy";
        // szString is a pointer to the 'R'  (automatically)
        // szString[0] = 'R'

  8. #8
    C/C++ homeyg's Avatar
    Join Date
    Nov 2004
    Location
    Louisiana, USA
    Posts
    209
    Thanks for your answers, most of my questions are cleared up. I have one more; in my example program in the first post, the entire szString array is printed out by just writing

    Code:
    cout<<szString;
    Based on what I know and how szString is a pointer to the first element in the array, wouldn't doing that print out the address? I know it doesn't, but this is more 'why' question.

  9. #9
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    The << operator's function will be overloaded to accept, among other things, a pointer to the first element of a string. If it receieves this input, it will output the string and use the pointer as it was intended.

  10. #10
    Magically delicious LuckY's Avatar
    Join Date
    Oct 2001
    Posts
    856
    That is a very good question, homey. Clearly it would be ridiculous if you wanted to print an array of characters (a "string") to have to print them one character at a time. A character array is a special thing and so it is treated accordingly. When you cout << szString the compiler knows you are attempting to print the string and not the address. But if you did this
    Code:
    cout << (void*)szString;
    it would print the address contained in szString.

  11. #11
    Registered User
    Join Date
    Dec 2004
    Location
    UK
    Posts
    109
    Quote Originally Posted by Stack Overflow
    » I beg to differ. There is a strong relationship between pointers and arrays. Any operation that can be acheived by array subscripting can also be done with pointers. The pointer version will in general be faster but, at least to the uninitiated, somewhat harder to understand.
    I said that an array is a pointer because that's what I've read in at least 2 books. I guess they just glossed over the important details.

    Sorry about that.

  12. #12
    Magically delicious LuckY's Avatar
    Join Date
    Oct 2001
    Posts
    856
    Quote Originally Posted by sigfriedmcwild
    I said that an array is a pointer because that's what I've read in at least 2 books. I guess they just glossed over the important details.

    Sorry about that.
    I don't think you have anything to apologize for, and I just wanted to mention that you may have the concept correct in your mind, but you are stating it incorrectly. An array is a series of allocated pieces of memory that are accessible only via a pointer, but an array is not a pointer, nor is a pointer an array. A pointer is a variable that contains an address, so clearly it cannot be said of a series of data in memory somewhere that it is the same as a pointer.

  13. #13
    C/C++ homeyg's Avatar
    Join Date
    Nov 2004
    Location
    Louisiana, USA
    Posts
    209
    Another quick (and not to mention the last) question: are the elements of the pointer allocated on the stack or the heap?

  14. #14
    Magically delicious LuckY's Avatar
    Join Date
    Oct 2001
    Posts
    856
    Your question is so indirect that a direct answer is not possible. What do you mean by "the elements of the pointer?" Do you mean the elements of the array to which a pointer refers or do you mean the address contained within a pointer?

  15. #15
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    That depends on how it's declared.
    Code:
    char* ptr = new char[200];  //on heap
    char array[200] = "Hello world!";  //on stack (not really a "pointer")
    char* ptr2 = "The Empire Strikes Back";  //somewhere
    In the third example, I don't believe there is any rule for where "The Empire Strikes Back" must be stored; as such, it may be stored in a read-only location, or anywhere else the compiler sees fit - and therefore the characters referred to by ptr2 may NOT be modified. On the other hand, if you reassign ptr2 to point to an array, or to a dynamically allocated memory block, then you can modify the characters that it points to.
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ ini file reader problems
    By guitarist809 in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2008, 06:02 AM
  2. char ** and argv memory question
    By simo_mon in forum C Programming
    Replies: 3
    Last Post: 08-17-2008, 08:47 AM
  3. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  4. Passing pointers to arrays of char arrays
    By bobthebullet990 in forum C Programming
    Replies: 5
    Last Post: 03-31-2006, 05:31 AM
  5. Newb Question - Cant convert Char[41] to Char
    By Kalkran in forum C++ Programming
    Replies: 2
    Last Post: 08-19-2004, 10:05 AM