Search code examples
cpointersheap-memoryc-stringsfunction-definition

C updating string incrementally


I am trying to update string step by step in C. The code i tried is below:

#include <stdlib.h>
#include <stdio.h>

int writech(char **text, char ch) {
    **text = ch;

    return 1;
}

char *write(int array[], size_t size) {
    char *string = (char*)malloc(sizeof(char)*(size+1));
    int i, n;

    for (i = 0; i < size; ++i) {
        n = writech(&string, '0' + array[i]);
        string += n;
    }

    return string;
}

int main() {
    int arr[] = { 1, 2, 3, 4, 5 };
    char *str = write(arr, sizeof(arr)/sizeof(arr[0]));

    printf("%s\n", str);

    return 0;
}

Here, write function should update string by calling other function and return updated string at the end. The code compiled and run successfully, though str (at the end of main) is empty after all. Actually, my task is to create string that contain table of some data and return it at the end. Pseudo code for my idea is below:

char *render_table() {
    char *table = malloc(sizeof table);

    write_header(table);
    write_row(table, some_data);
    write_row(table, some_data);
    write_footer(table)

    return table;
}

For implementing this pseudo code I wrote the above code, but not able to update passed string successfully. I know pointers are passed to function as copies, and passed memory of my string (writech(&string) to function, but string not updated still. What am i missing?

P.S. Tweaking with pointers is really struggling for me as beginner in C. What would you suggest?


Solution

  • string is updated. The problem is the pointer string is updated and the information of the beginning of the string is lost. You have to hold the information.

    One more point is that terminating null-character must be added to pass the buffer for %s (without specifying length to print).

    Also note that casting results of malloc() in C is discouraged.

    Try this:

    char *write(int array[], size_t size) {
        char *string = malloc(sizeof(char)*(size+1));
        char *cursor = string;
        int i, n;
    
        for (i = 0; i < size; ++i) {
            n = writech(&cursor, '0' + array[i]);
            cursor += n;
        }
        writech(&cursor, '\0');
    
        return string;
    }