1

I'm new to C coming from Java. Just explain me why this:

text[0] = 'a';

is not possible, my program just crashes.

#include "caesarHead.h"
#include <limits.h>

int main(void) {

 caesar("Hello this is a sample text", 12);

 printf("\n\n");
}


void caesar(char text[], char offset) {
 int i = 0;
 text[0] = 'a';
 char *p = text;

 for (p; *p != '\0'; p++) { 
   
  printf("String: %c \n", text[i]);
  printf("Ascii: %i \n", (int)text[i]);
  i++;
 }
}
PssstZzz
  • 349
  • 1
  • 3
  • 11

1 Answers1

2

You cannot modify string literal. In fact, you can try but this is undefined behavior and it may or may not work.

Instead, put your string to variable first and then use it. In this case, you string is initialized when main is called and it is put on stack therefore you are able to modify it later.

int main(void) {
    char str[] = "Hello this is a sample text";
    caesar(str, 12);
    printf("\n\n");
}

String literal must be used as non-modifiable string. When trying to modify such a string, we have undefined behavior.

unalignedmemoryaccess
  • 7,246
  • 2
  • 25
  • 40
  • I don't get it, I have a char Array. at Index 0 of that char array I try to set the element to 'a' and it doesn't work. Why ? And to what exactly are you trying to refer as String, isn't that a char array ? – PssstZzz Jul 06 '17 at 20:40
  • 1
    Because you used *string literal* and not string from RAM. *String literal* may be put to section which can't be modified. @PssstZzz – unalignedmemoryaccess Jul 06 '17 at 20:41
  • @PssstZzz This is a non-modifiable char array. String literals are those. – bipll Jul 06 '17 at 20:41