Language/C & C++

[C] Convert matrix from text file

Rogue 2022. 10. 23. 21:00
반응형
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
	// Allocate memory for the array like this:

	int** array;

	array = malloc(9 * sizeof(*array));
	if (!array) /* If 'malloc' failed */
	{
		fputs(stderr, "Error allocating memory; Bailing out!");
		exit(-1);
	}

	int count = 1;
	for (int i = 0; i < 9; i++)
	{
		array[i] = malloc(count * sizeof(**array));
		if (!array[i])	/* If 'malloc' failed */
		{
			for (int j = 0; j < i; j++)	/* free previously allocated memory */
			{
				free(array[j]);
			}
			free(array);

			fputs(stderr, "Error allocating memory; Bailing out!");
			exit(-1);
		}
		count++;
	}
	
	// Then, read data from the file into the array by using:

	FILE* fp = fopen("C:\\Users\\hrmk\\OneDrive\\바탕 화면\\fox.map", "rt");
	if (!fp)
	{
		for (int i = 0; i < 9; i++)	/* free previously allocated memory */
		{
			free(array[i]);
		}
		free(array);

		fputs(stderr, "Error allocating memory; Bailing out!");
		exit(-1);
	}

	int max = 1;

	for (int i = 0; i < 9; i++)
	{
		for (count = 0; count < max; count++)
		{
			fscanf(fp, "%d", &array[i][count]);
		}
		max++;
	}

	

	// And finally, free the allocated memory:

	for (int i = 0; i < 9; i++)
	{
		free(array[i]);
	}

	free(array);


	return 0;
}
반응형