0

I'm trying to understand why the declaration method of my strings does and doesn't allow me to modify them, let me explain more.

If I declare an array of strings like so: char *Strs[] = {"Str1", "Str2", "Str3"}; I can read the strings and print them to screen using printf etc. I can't however modify them how I'd expect to, for example: Strs[0][0] = 'A' does nothing to the string once I print it (I will paste my test code below...)

If however, I declare the array: char Strs[3][5] = {"Str1", "Str2", "Str3"}; I can read and modify the strings using the array method.

Why does my method of modification not work in the first instance?

int main(int argc, char **argv)
{
    /* Doesn't work
    char *Strs[] = {"Str1", "Str2", "Str3"};

    printf("Premod: %s\n", Strs[0]);
    Strs[0][0] = 'A';

    printf("Postmod: %s\n", Strs[0]);
    */
    //Works
    char Strs[3][5] = {"Str1", "Str2", "Str3"};

    printf("Premod: %s\n", Strs[0]);
    Strs[0][0] = 'A';

    printf("Postmod: %s\n", Strs[0]);

    return 0;
}
Pyrohaz
  • 232
  • 2
  • 11
  • `char *Strs[]` is an array of pointers to the string literals you gave it (which afaik are read only). `char Strs[3][5]` is a 2D array being initialized to the strings you give it. – Colonel Thirty Two Oct 16 '14 at 18:43

1 Answers1

0

When you declare a string like

char* str = "hello";

You are creating something called a string literal, which in C cannot be modified.

But thats not the case if you create it something like this

char str[] = { 'h', 'e', 'l', 'l', 'o'};

You can modify this character array

Haris
  • 12,120
  • 6
  • 43
  • 70
  • Thanks for the reply @haris! Is a string literal considered constant and that is why I can't modify it? – Pyrohaz Oct 16 '14 at 18:49
  • @Pyrohaz: Modification of string literals is not allowed because literals are placed in read-only storage. – Haris Oct 16 '14 at 18:52