0

After doing this,

char* example = (char*)malloc(10);

How can I change the 5th byte to 'a', so that printf("%s", example); would give me " a "?

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • 1
    What `malloc()` returns is not a string but an uninitialized buffer. You have to initialize it with some string first before changing the "string". – MikeCAT Mar 06 '18 at 22:55
  • 1
    `a[4] = 'a';`. But you'll need to add those spaces too, and don't forget the null terminator (`a[9] = '\0';`). Also, there's no need to cast the result of `malloc()`. Try `char *example = malloc(10);` instead. – r3mainer Mar 06 '18 at 22:55
  • 1
    How to initialize all bytes to empty " "? –  Mar 06 '18 at 22:56
  • 1
    There is no need to cast the return of `malloc`, it is unnecessary. See: [**Do I cast the result of malloc?**](http://stackoverflow.com/q/605845/995714) and... `memset (example, ' ', 9);` and `example[9] = 0;` Then `example[4] = 'a';` – David C. Rankin Mar 06 '18 at 22:56
  • Which book are you reading? The reason I ask is, this question you've asked indicates that you're struggling in a way which book readers usually don't... I'm suggesting that you're *not* reading a book, based on my observations. Am I correct? – autistic Mar 06 '18 at 22:57
  • 1
    *How to initialize all bytes to empty " "?* — `memset(example, ' ', 9); a[9] = '\0';` – r3mainer Mar 06 '18 at 22:57

3 Answers3

3

You can do it simply like below:-

memset(example, ' ',10);
example[9] = 0; //assign end of string character equal to '\0'
example[4] = 'a';

How will it work? memset will fill all the bytes with white space and example[9] = 0; will assign a end of string character into it and example[4] = 'a'; will assign 'a' at 5th location.

Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 17
2

The memory returned by malloc is unitialized. Besides setting the 5th byte to 'a', you need to set the others to a space, and you'll need to add a null terminating byte.

The simplest way to do this would be strcpy:

strcpy(example, "    a    ");
dbush
  • 205,898
  • 23
  • 218
  • 273
0

To change an individual element, just use regular array subscript notation:

example[4] = 'a';

Note, however, that malloc does not initialize the memory to be any particular value - it (most likely) won't be all blanks or all 0's. It will be indeterminate. If you want the elements surrounding 'a' to be blanks, you'll have to assign them explicitly as well. Also, remember to write the 0 terminator at the end, or example won't contain a string.

You can use strcpy to assign new strings to example:

strcpy( example, "    a    " ); // 9 characters plus string terminator

or you could assign element by element:

for ( size_t i = 0; i < 3; i++ )
  example[i] = ' ';

example[4] = 'a';

for ( size_t i = 5; i < 9; i++ )
  example[i] = ' ';

example[9] = 0; // don't forget the string terminator!
John Bode
  • 119,563
  • 19
  • 122
  • 198