-2

i try to print simple c* string like this :

char *cc = "HEllo";

                for (char* inputPtr = cc; inputPtr[0]; inputPtr++) {
                    char c = inputPtr[0]++;
                    printf("%s",c);
                }

but im getting : Access violation writing location 0x00CFB310. on :

char c = inputPtr[0]++;

what is wrong here ?

user63898
  • 29,839
  • 85
  • 272
  • 514

4 Answers4

2

It looks like you are experimenting with inputPtr[0] as a substitution for *inputPtr. In many contexts, the two expressions produce the same result.

However, expression inputPtr[0]++ is not the same as *inputPtr++, because [0] has higher precedence than *, but it has the same precedence as suffix ++. Operators within this precedence level are applied left-to-right, so the first expression post-increments inputPtr[0], a character inside a character literal. This is undefined behavior, hence you see a crash.

If you replace inputPtr[0]++ with *inputPtr++ and remove inputPtr++ from loop header, your code is going to work fine:

for (char* inputPtr = cc; inputPtr[0]; ) {
    char c = *inputPtr++;
    printf("%c", c); // Replace %s with %c to print one character
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

inputPtr is pointing at "HEllo", which is a string literal.

Modifying string literal isn't allowed and trying to do so invokes undefined behavior.

inputPtr[0]++ is trying to modify string literal. If data of string literal is located in read-only locations, it may lead to Segmentation Fault.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
0

String literals in C are read only, attempting to modify the characters in string literals leads to undefined behavior.

Any with inputPtr[0] you do modify the string since you increment the character inputPtr[0].

This is the reason you should always use const char * when pointing to string literals.

If you want to modify the contents of the string you have to create an array:

char cc[] = "HEllo";
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

As the others have written, you can't modify a string literal. Change your declaration to char cc[] = "HEllo"; and see what happens. The suggested declaration declares a string buffer that is modifiable.

lukeg
  • 4,189
  • 3
  • 19
  • 40