Thread: Array vs pointer in C, very short questions?

  1. #1
    Registered User
    Join Date
    Feb 2013
    Posts
    17

    Array vs pointer in C, very short questions?

    Which one (Array or pointer) is located in read only portions of memory ?

    In other words

    char* x = "hello";
    x[1] ='m';
    I get error here

    but when I use array like
    char x[] ="hello";
    x[1] ='m';
    I don't get error

    Also when I use malloc I get error too
    char* x =malloc(sizeof(char)*10);

    -----------------------
    So what is the difference if I use malloc and don't use like char x[] ="hello"; and why I get error when I use either one and I don't get error when I use array?

  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 need to post ACTUAL error messages.

    "I got an error" isn't enough information to tell you how you messed up.
    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
    Registered User
    Join Date
    Mar 2013
    Posts
    1

    Re: Array vs. Pointer

    Quote Originally Posted by AmirHossein H-m View Post
    Which one (Array or pointer) is located in read only portions of memory ?

    In other words

    char* x = "hello";
    x[1] ='m';
    I get error here

    but when I use array like
    char x[] ="hello";
    x[1] ='m';
    I don't get error

    why I get error when I use either one and I don't get error when I use array?
    Hi Amir,

    When you assign a character string pointer (char* x = "hello"), it's really just a pointer pointing to the memory location of "hello". As such, the string is read only. In your first example, you're treating the pointer as if it were an array, when it's really just a pointer to a character array.

    To change the string, you would need to copy it (or initialize it) in an array and change it like you did in your second example.

    I don't think that this is an appropriate situation for malloc(). Hope this helps.

    Empty

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Three short questions C-ers
    By Aitra in forum C Programming
    Replies: 2
    Last Post: 01-27-2013, 10:32 AM
  2. Replies: 14
    Last Post: 03-08-2010, 06:32 PM
  3. Casting pointer to unsigned short
    By cks2k2 in forum C Programming
    Replies: 6
    Last Post: 03-25-2009, 05:33 AM
  4. Short questions...
    By Devil Panther in forum C++ Programming
    Replies: 7
    Last Post: 09-03-2005, 02:47 PM
  5. A Few Short Questions....
    By SithVegeta in forum C Programming
    Replies: 6
    Last Post: 11-14-2004, 11:52 PM