Search code examples
carrayspointersmallocrealloc

C - how to add to the end of a char array after realloc()


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?


Solution

  • You added the characters after the null terminator. Printing a string stops at the null.

    Assign the new characters to array[1+pos] instead of array[2+pos]. This also goes for adding the new null terminator after the loop, it should be

    array[1+pos] = '\0';
    

    You could also use strcat() instead of the loop:

    strcat(array, stringToAdd);
    

    It will find the null terminator automatically so you don't have to know the offset, and add the new null terminator properly.

    sizeof(array) is the size of the pointer (8 bytes), not the length of the string. If you want the string length, you should use strlen(array). See difference between sizeof and strlen in c