Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment char pointer

Tags:

c

char

increment

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?

like image 463
Corry Chapman Avatar asked Nov 29 '22 23:11

Corry Chapman


2 Answers

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.

like image 75
Taelsin Avatar answered Dec 05 '22 03:12

Taelsin


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.

like image 36
SandBag_1996 Avatar answered Dec 05 '22 02:12

SandBag_1996