Increment char pointer

22,117

Solution 1

It can be, you're just incrementing the wrong thing. (*tester)++ increments the data to which tester is pointing. I believe what you wish to do is *(++tester) which will increment the pointer and then dereference it.

Solution 2

char *tester = "hello";

Here tester is pointing to a string constant. It is stored in a read-only memory. Any write modifications causes undefined behavior.

As @Taelsin pointed, it seems you want to increment the pointer itself, and not what it is pointing to. You need *(++tester).

After OP's clarification:

In case you want to increment the H to I, then (*tester + 1) would do the job.

Solution 3

If you want to increment the character, you can add 1 to it instead of using the increment operator:

char *tester = "hello";
char a = (*tester) + 1; // instead of (*tester)++
printf("Char is %c\n", a);

Hope this is what you are searching for.

Explanation

In another answer, zenith commented an explanation why it is not possible to use the increment operator:

String literals like "hello" are initialized in a read-only memory. It is not possible to increment its value. That is why you have to copy the value first, if you want to change it. char a = (*tester) + 1; takes the value of the first character, adds 1 to it and saves it to a.

Solution 4

char a = (*tester)++; does not increase the pointer as you assume; it increases the dereferenced pointer instead, that is, the value a pointer points to.

You are actually trying to make changes to a string literal, which may resides in the read-only memory, causing undefined behaviour.

See n1570, 6.4.5 String literals:

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

To increase the pointer, use char a = *(tester++);, or just char a = *tester++; thanks to the operator precedence.

Solution 5

I guess you are trying to do something like this..

const char *tmp = "Hello world. This is a great test";
   int count = strlen(tmp);
   while(count>0)
   {
      printf("%s\n",tmp);
      tmp++;
      count--;
   }
Share:
22,117
Corry Chapman
Author by

Corry Chapman

Updated on March 15, 2021

Comments

  • Corry Chapman
    Corry Chapman about 3 years

    The following code gives a seg fault at second line:

     char *tester = "hello";
     char a = (*tester)++;  // breaks here
     printf("Char is %c\n", a);
    

    The following code works:

     char *tester = "hello";
     a = *tester;
     a++;
     printf("Char is %c\n", a);
    
     // prints i
    

    Why can't it be done in one operation?