Thread: Array of pointers + strcpy = access violation?

  1. #1
    Registered User
    Join Date
    Dec 2001
    Posts
    15

    Array of pointers + strcpy = access violation?

    Why does the following code, when run, give an access violation? I've looked at it with the debugger, and leading into the strcpy instruction everything looks as it should...
    Code:
    int main(void)
    {
    char *strarray[3] = {"one", "two", "three"};
    cout << strarray[0]; //Prints "one" as it should...
    strcpy(strarray[0], "new"); //Access violation?
    return(0);
    }

  2. #2
    Registered User Dr. Bebop's Avatar
    Join Date
    Sep 2002
    Posts
    96
    You get an access violation because string literals can be put in read only memory by the compiler, they aren't supposed to be modified. What you have is an array of 3 pointers that point to string literals, not to writable memory that you own, so if you try to change it the chances are good you will get an access violation type error.
    Processing error: Stupidity detected.
    ------------------------------
    Dr. Bebop
    Windows XP Professional Ed.
    Microsoft Visual Studio 6

  3. #3
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Please post C++ code on the appropriate board next time.

    In addition to the previous answer, here's a reference link.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Syntax for constant array of array pointers
    By BMintern in forum C Programming
    Replies: 4
    Last Post: 05-14-2008, 08:21 AM
  2. Cannot access pointers from an array
    By Datamike in forum C++ Programming
    Replies: 4
    Last Post: 11-05-2005, 02:16 AM
  3. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  4. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  5. 2d Array access by other classes
    By deaths_seraphim in forum C++ Programming
    Replies: 1
    Last Post: 10-02-2001, 08:05 AM