C function split array into chunks

不问归期 提交于 2021-02-08 09:44:12

问题


I have an array of bytes aka unsigned char called content. I want to split my content array into 2 new arrays in a separate function. This function should also determine the size for each of the 2 chunks and allocate memory for them. Also, I want to be able to use both the new arrays and their sizes outside of the function. My implementation is giving me segmentation fault and I must be doing something with pointers wrong.

Main function

int main(int argc, char *argv[]) {

    byte *content = NULL;
    size_t size_content;

    byte *param = NULL;
    size_t size_param;

    byte *data = NULL;
    size_t size_data;

    // This works fine!
    size_content = load_file_to_memory(argv[1], "rb", &content);

    // split content
    split_content(content, &param, &data,
            size_content, &size_param, &size_data);

    // SEGMENTATION ERROR
    putchar(param[0]);

    return 0;
}

Split Content Function:

    void split_content(byte *content, byte **param, byte **data,
            size_t size_content, size_t *size_param, size_t *size_data) {
    *size_param = get_number_of_param_bytes(content);
    *size_data = size_content - *size_param;

    *param = malloc((*size_param) * sizeof(byte));
    *data = malloc ((*size_data) * sizeof(byte));

    for(size_t i=0; i<*size_param; i++) {
        *param[i] = content[i];
    }

    for(size_t i=*size_param; i<size_content; i++) {
        *data[i-*size_param] = content[i];
    }
}

Get number of param bytes function:

    size_t get_number_of_param_bytes(byte *content) {
    size_t num_whites = 0;
    size_t byte_index = 0;
    do {
        byte b = content[byte_index];
        if(isspace(b)) {
            num_whites += 1;
        }
        byte_index += 1;
    } while (num_whites < N_WS);
    return byte_index;
}

Load file to memory:

    size_t load_file_to_memory(const char *filename, const char *mode, byte **buffer) {
    size_t size = 0;

    FILE *file = fopen(filename, mode);
    if (file == NULL) {
        *buffer = NULL;
        printf("Unable to open file! Terminating...\n");
        exit(-1);
    }

    size = get_file_size(file);
    *buffer = malloc(size * sizeof(byte));

    if (fread(*buffer, sizeof(byte), size, file) != size) {
        printf("Error loading file into memory! Terminating...\n");
        free(*buffer);
        exit(-1);
    }

    fclose(file);
    return size;
}

It must be something with the pointers that I am doing wrong here.


回答1:


Because of precedence rules, *param[i] means *(param[i]), but you actually want (*param)[i].

Likewise, *data[i-*size_param] means *(data[i-*size_param]) but you want (*data)[i-*size_param].

Add the extra brackets around *param and *data.



来源:https://stackoverflow.com/questions/33534660/c-function-split-array-into-chunks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!