2

Is it possible anyhow to increment ASCII value of a char in C? Let's say I have following code

int main(){

    char *a = "This is my test string";

    /* *(a+12) += 21; This isnt going */

    printf("%c = %c\n", *(a+12), *(a+12)+21);

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

    return 0;
}

What I want, for example, is to increment the e character with 21 which would be z and make it permanent inside that array. So when I use printf on the array, it prints z on that place instead of e.

How would we go about this?

Jumpman
  • 429
  • 1
  • 3
  • 10

2 Answers2

0

Change char *a = "This is my test string"; to `char a[] = "This is my test string";

artm
  • 17,291
  • 6
  • 38
  • 54
  • Yeah, right declaring it as a pointer made it just read-only -.- But one short question, if it'd be on heap, then I would be able to operate still, right? – Jumpman Dec 09 '15 at 01:55
  • the character array is always on the stack, not the heap here. – artm Dec 09 '15 at 01:58
  • Check this Q which dig in the differences between char * and char[] initialization: http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c – artm Dec 09 '15 at 02:02
  • Yeah I know I was just wondering how would it behave with a dynamic array? – Jumpman Dec 09 '15 at 02:20
  • you can change dynamic array the same way. Example, `char *b = malloc( 100 );` `memcpy( b, a, strlen(a) + 1);` `*( b + 12 ) += 21;` – artm Dec 09 '15 at 02:29
  • @Maxitj now that you are no longer a newbie (ie you can vote) consider vote up your accepted answer – artm Nov 15 '16 at 05:47
0

Change your

*a to a[]="This is my test string";

and by using

a[12] = a[12] + 21;

You will find the change in the array;

Nutan
  • 778
  • 1
  • 8
  • 18