How to dynamically allocated matrix inside a struct in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct matrixplusstruct {
	int plus;
	char** matrix;
} matrixplus;


#define SIZE 5
#define LEN 6

int main(void)
{
	matrixplus mp;

	mp.plus = 100;

	mp.matrix = malloc(SIZE * sizeof(char*));

	for (size_t i = 0; i < SIZE; i++) {
		mp.matrix[i] = malloc(LEN * sizeof(char));
	}

	for (size_t i = 0; i < SIZE; i++) {
		strcpy(mp.matrix[i], "abcde");
	}

	printf("%d\n", mp.plus);
	for (size_t i = 0; i < SIZE; i++) {
		puts(mp.matrix[i]);
	}

	for (size_t i = 0; i < SIZE; i++) {
		free(mp.matrix[i]);
	}

	free(mp.matrix);

	return 0;
}





/*
run:
  
100
abcde
abcde
abcde
abcde
abcde
  
*/

 



answered Nov 19, 2022 by avibootz
...