Home > Back-end >  Change char at index from char pointer
Change char at index from char pointer

Time:03-31

I know that the following is invalid:

char *string = "Some String":
string[1] = 'v';//INVALID

But how can I achieve the desired behavior here, without changing the type of string to some sort of char array?

The final value in string should be 'Svme String'

CodePudding user response:

The only way is to store the string literal in a character array and then you can use a pointer to the array to change the stored string.

For example

char s[] = "Some String":
char *string = s;
string[1] = 'v';

or

const char *s = "Some String":

char *string = malloc( strlen( s )   1 );
strcpy( string, s );
string[1] = 'v';

//...

free( string );

CodePudding user response:

These two things that look almost identical

char *stringLit = "Some String";
char stringArr[] = "Some String";

are very different

in the first case stringLit occupies the size of one pointer (32 or 64 bits). This pointer is set to point at a literal string allocated by the compiler almost certainly in a memory area that is read only , usually in the same set of memory chunks where the execution code is. This is why modifying the string doesnt work (on most systems), you are trying to modify something in a read only memory area

In the second case stringArr occupies 12 bytes. The compiler will arrange for those 12 bytes to be loaded from the literal "Some String". When and how this is done depends on where stringLit is declared.

If its like this

 void fooo(){
       char stringArr[] = "Some String";
       ...
 }

then 12 bytes will be reserved in the stack when the function starts and the literal will be copied into them. This will happen every time this function is called.

If its like this

  #include <stdio.h>
  ....     
  char stringArr[] = "Some String";

or

 void fooo(){
       static char stringArr[] = "Some String";
       ...
 }

then the compiler will allocate 12 bytes in the programs static data area (where globals are stored) and usually load the literal into that memory during compilation, or perhaps when the program starts, but its only done once.

  • Related