I have a short char array called "array". I'm trying to realloc more space to it then add more chars onto the end. for some reason when I print the array, these extra characters don't show up, although they do display when I index them individually.
#include <stdio.h>
#include <stdlib.h>
int main(){
char *array = malloc(2);
array[0] = 'b';
array[1] = '\0';
char stringToAdd[] = "honey";
array = realloc(array, (16));
int pos;
//add stringToAdd into array one char at a time
for (pos = 0; pos < 5; pos++){
array[2+pos] = stringToAdd[pos];
printf("%d ", 2+pos);
printf("%c ", array[2+pos]);
printf("%s\n", array);
}
array[pos] = '\0';
int k = sizeof(array);
//should print out the string "bhoney" and its length
printf("%s, length = %d\n", array,k);
free(array);
return 0;
}
output is:
2 h b
3 o b
4 n b
5 e b
6 y b
b, length = 8
also the length of the array seems to be 8 no matter how much space I try to realloc to it?