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 "
?
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 "
?
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.
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 ");
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!