String literal vs string in array (C)

String literals can not modify their data, but they can modify their pointer. On the other hand, if you had an array, then the opposite stands true. You can not modify the pointer, but you can modify the data.

An interesting comment on this was: “String literals have a type. It’s array of char. And while you said “String literals can not modify their data, but they can modify their pointer,” my main problem with this is that they don’t have a pointer like you implied. The pointer and the string literal are actually separate things.”

strLiteral.c

#include <stdio.h>

int main(void)
{
    char* strLiteral = "I am a string literal!";
    char* origin = strLiteral;

    printf("I am about to chrash...!\n");
    *(strLiteral+1) = 'W';
    printf("Did I?\n");

    printf("%s\n", origin);

    return 0;
}

Which outputs this:

linux05:/home/users/std10093>px
I am about to chrash...!
Segmentation fault

strArray.c

#include <stdio.h>

int main(void)
{
    char str[15] = "a string";
    
    printf("I can modify the data...\n");
    *(str+1) = 'W';
    
    printf("But not the pointer...!\n");
    str++;
    
    printf("%s\n", str);
    
    return 0;
}

Which outputs this:
-On Linux

linux05:/home/users/std10093>gcc -Wall px.c -o px
px.c: In function 'main':
px.c:11: error: lvalue required as increment operand

-On windows

main.c: In function `main':
main.c:11: error: wrong type argument to increment
make[2]: *** [build/Debug/Cygwin-Windows/main.o] Error 1
make[1]: *** [.build-conf] Error 2
make: *** [.build-impl] Error 2

str.c

#include <stdio.h>
#include <ctype.h>

int main(void) {
   char foo[] = "My sample string.";
   char* bar;

   for(bar = foo; *bar != '\0'; bar++)
   {
      *bar = toupper(*bar);
   }
   printf("%s\n", foo);

   return 0;
}

which is legal and produces the string in capital letters, as expected.
This two first examples were developed by me, G. Samaras. The third example, as well as this link, come from whiteflags (of C board).

Have questions about this code? Comments? Did you find a bug? Let me know!😀
Page created by G. (George) Samaras (DIT)

2 thoughts on “String literal vs string in array (C)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s