0

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);

}
3
  • To start with, you do know that array indexes in C starts at zero? So the index of the 'W' in "Hello World" is 6. Although you would notice that very quickly with this program after fixing the syntax. Commented Aug 26, 2015 at 14:34
  • 1
    Also, arrays and pointers are very often interchangeable, and you can use array indexing syntax to access elements when using pointer, as well as using an array as a pointer. Commented Aug 26, 2015 at 14:37
  • 2
    memcpy(&code[6], "Wales", 5); Commented Aug 26, 2015 at 14:41

1 Answer 1

2

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';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.