Sam Roberts
Sam Roberts

Reputation: 399

How can I replace characters in a string using a pointer? (in c code)

How can I replace characters in a string using a pointer? (in c code)

Here's my code:

#include <stdio.h>
#include <string.h>

unsigned char code[] = "Hello world!\n";
main()
{

        printf("String Length:  %d\n", strlen(code));
        printf("Original String: %s\n", code);

        char &code[7] = "W";    
        char &code[8] = "a";
        char &code[9] = "l";
        char &code[10] = "e";
        char &code[11] = "s";

        printf("New String: %s\n", code);

}

Upvotes: 0

Views: 2549

Answers (1)

Andy Thomas
Andy Thomas

Reputation: 86381

You can specify a zero-based array index:

   code[6] = 'W';    
   code[7] = 'a';
   code[8] = 'l';
   code[9] = 'e';
   code[10] = 's';

Character literals are specified with single quotes rather than double.

The array variable is a synonym for the address of the first element. If you specifically want to use pointer syntax, you can replace code[i] with *(code + i). For example:

   *(code + 6) = 'W';    
   *(code + 7) = 'a';
   *(code + 8) = 'l';
   *(code + 9) = 'e';
   *(code + 10) = 's';

Upvotes: 2

Related Questions