Arrays and pointers in C using Malloc

I have this code which works. But I’m confused about how pointer arrays work, dont you have to initialise the array? How is this block of code able to just have ‘&arr[i]’. Secondly, why don’t we need to derefernce the pointer to manipulate the data stored in the location the pointer is pointing to (the… Read More Arrays and pointers in C using Malloc

Passing an array of structs where one of the fields is another array, to a function

This is my struct. typedef struct { uint8_t *data; size_t size; } buffer; I initialize it like this in my main function. buffer *array; array = calloc(255, sizeof(*array)); //check for error for (int i = 0; i < 255; i++) { array[i].data = malloc(sizeof(*array->data)); //check for error } Then I pass it to a function.… Read More Passing an array of structs where one of the fields is another array, to a function

malloced char * object filled with random text and of an apparent different size

I have the following code, and am specifically having problems with the print_file_results function. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <getopt.h> int bytes_flag,lines_flag, words_flag; int arg_in; static struct option long_opts [] = { {"bytes", no_argument, 0, ‘c’}, {"lines", no_argument, 0, ‘l’}, {0,0,0,0} }; int count_bytes(const char *filename){ FILE * file_stream; int byte_count = 0;… Read More malloced char * object filled with random text and of an apparent different size

Why do I always hear to avoid allocating memory when I can in C?

I am always told to not allocate memory whenever I can achieve the exact same thing without it. Do people say that because freeing things in your code can take some time, or is there an efficiency-oriented explanation? (e. g. better performance) >Solution : Because managing memory is complicated and prone to all kinds of… Read More Why do I always hear to avoid allocating memory when I can in C?

C code not throwing error for initializing extra string character than it is supposed to be

I was running this code to expect an error but to my surprise, it didn’t. Even if I initialize a string*(5 bytes)* that is greater than what was allocated using malloc (4bytes). #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char * name = malloc(4); name = "hello"; printf("%s\n",name); return 0; } This is… Read More C code not throwing error for initializing extra string character than it is supposed to be

looping array of pointers to free them makes program crash in c

Full code: #include <stdio.h> #include <stdlib.h> #include <string.h> void printarray(int* array, int arraysize){ for (int i = 0; i<arraysize; i++){ printf("%d\n", *array); array++; } } void printStrArray(char** array, int arraysize){ int j = 0; for (int i = 0; i<arraysize; i++){ j = 0; while (array[i][j] != ‘\0’){ printf("%c", array[i][j]); j++; } printf("\n"); } }… Read More looping array of pointers to free them makes program crash in c