0

I'm self-learning C from a book and currently studying pointers and arrays.

#include <stdio.h>
#include <string.h>
#define LINES 5
void main()
{
    char* str[LINES];
    str[0] = "hola";
    str[1] = "mundo";
    *(*(str + 0) + 1) = 'Z';
    printf("%c", *(*(str + 0) + 1));
}

Here I want to replace 'o' of "hola" with 'Z' but it's not working. if i remove: ((str + 0) + 1) = 'Z'; I get 'o' in the output but how do i replace the character of the string?

  • Note that modify a string literal is implemented behavior, and a lot of implementation define them as undefined behavior. If you want to play with string you need to learn to create them first, if available use `strdup()` – Stargateur Jun 25 '18 at 11:27
  • 'strdup()' duplicates a string and returns a pointer to the string but in my code i just want to replace a character. How will 'strdup()' help? – Debasis_Buxy Jun 25 '18 at 11:38
  • It's help you to not segfault. – Stargateur Jun 25 '18 at 11:39
  • C have some syntactic sugar for this: instead of `*(*(str + 0) + 1) = 'Z'`, you may use: `str[0][1] = 'Z'` – SKi Jun 25 '18 at 12:23
  • there are only 2 valid signatures for `main()` they both have a return type of `int`, not `void` – user3629249 Jun 25 '18 at 15:48

1 Answers1

5

Your program is having undefined behavior as you are trying to modify a String Literal:

    str[0] = "hola";
    str[1] = "mundo";
    *(*(str + 0) + 1) = 'Z';   // This is UB

From C Standards#6.4.5p7 [String Literals]

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

As suggested by Stargateur, you can use strdup() like this:

    str[0] = strdup("hola");
    str[1] = strdup("mundo");

strdup() duplicates the given string. It uses malloc to obtain memory for the new string. Make sure to free it once you are done with it, like this:

    free (str[0]);
    free (str[1]);

Also, using void as return type of main function is not as per standards. The return type of main function should be int.

H.S.
  • 11,654
  • 2
  • 15
  • 32