Two-dimensional array as return value

For my homework, I have to read the data from the input file and save it in a two-dimensional array, and then pass this array to another function. This is what I have tried so far, but I do not know when I call this function basically, it gives an error:

The location of the access violation record is 0x00000000.

I tried to dynamically allocate memory, and it gives the same error. What am I doing wrong?

Last code update:

#include<stdio.h> #include<stdlib.h> int *a[2]; void getData(void) { FILE *fp = fopen("input.txt", "r"); int number; fscanf(fp, "%d", &number); for (int i = 0; i < number; i++) { a[i]=(int*)malloc(number * sizeof (int)); fscanf(fp, "%d %d", &a[i][0], &a[i][1]); } fclose(fp); } int main() { getData(); for(int i=0;i<8;i++) { printf("%d %d\n",a[i][0],a[i][1]); } } 
+4
source share
2 answers

You need to allocate memory for a

Before the for loop

 a = (int **)malloc(number * sizeof(int *)) 
+5
source

You do not highlight the first dimension, i.e. a is a null pointer when you try to dereference it.

 #include <stdlib.h> a = malloc(number * sizeof *a); 

BTW, sizeof(int) not enough to store two numbers.

 #include <stdlib.h> a[i] = malloc(2 * sizeof *a[i]); fscanf(iFile, "%d %d", &a[i][0], &a[i][1]); 

Here is the whole correct code (although not perfect if a is a global global variable):

 int (*a)[2] = NULL; void getData(void) { FILE *fp = fopen("input.txt", "r"); int number; fscanf(fp, "%d", &number); a = malloc(number * sizeof *a); for (int i = 0; i < number; i++) fscanf(fp, "%d %d", &a[i][0], &a[i][1]); fclose(fp); } 
+1
source

Source: https://habr.com/ru/post/1445369/


All Articles