Answers for "malloc 2d array"

C
2

c malloc for 2d array

#include <stdlib.h>

	int **array;
	array = malloc(nrows * sizeof(int *));
	if(array == NULL)
		{
		fprintf(stderr, "out of memoryn");
		exit or return
		}
	for(i = 0; i < nrows; i++)
		{
		array[i] = malloc(ncolumns * sizeof(int));
		if(array[i] == NULL)
			{
			fprintf(stderr, "out of memoryn");
			exit or return
			}
		}
Posted by: Guest on May-07-2021
0

malloc contiguous 2d array

int **A = malloc(ROWS * sizeof(int*));
A[0] = malloc(ROWS * COLS * sizeof(int));
for(int i = 1; i < ROWS; i++) 
   A[i] = A[i-1] + COLS;
// use A[i][j]
Posted by: Guest on October-19-2021
0

double pointer malloc in c

char *x;  // Memory locations pointed to by x contain 'char'
char **y; // Memory locations pointed to by y contain 'char*'

x = (char*)malloc(sizeof(char) * 100);   // 100 'char'
y = (char**)malloc(sizeof(char*) * 100); // 100 'char*'

// below is incorrect:
y = (char**)malloc(sizeof(char) * 50 * 50);
// 2500 'char' not 50 'char*' pointing to 50 'char'
Posted by: Guest on August-15-2020

Code answers related to "C"

Browse Popular Code Answers by Language