How to initialize const in a struct in C (with malloc)

You need to cast away the const to initialize the fields of a malloc’ed structure: struct deneme *mydeneme = malloc(sizeof(struct deneme)); *(int *)&mydeneme->a = 15; *(int *)&mydeneme->b = 20; Alternately, you can create an initialized version of the struct and memcpy it: struct deneme deneme_init = { 15, 20 }; struct deneme *mydeneme = malloc(sizeof(struct … Read more

allocate matrix in C

Well, you didn’t give us a complete implementation. I assume that you meant. int **mat = (int **)malloc(rows * sizeof(int*)); for(int i = 0; i < rows; i++) mat[i] = (int *)malloc(cols * sizeof(int)); Here’s another option: int *mat = (int *)malloc(rows * cols * sizeof(int)); Then, you simulate the matrix using int offset = … Read more

Dynamically create an array of strings with malloc

You should assign an array of char pointers, and then, for each pointer assign enough memory for the string: char **orderedIds; orderedIds = malloc(variableNumberOfElements * sizeof(char*)); for (int i = 0; i < variableNumberOfElements; i++) orderedIds[i] = malloc((ID_LEN+1) * sizeof(char)); // yeah, I know sizeof(char) is 1, but to make it clear… Seems like a … Read more