Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,945 questions

51,887 answers

573 users

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

Related questions

2 answers 157 views
1 answer 112 views
2 answers 135 views
1 answer 139 views
1 answer 189 views
...