Reputation: 2135
For my homework, I have to read data from an input file and to store it in a double dimensional array and then pass this array to another function. This is what I have tried so far, but I don't know when I call this function in main it gives the error:
Access violation writing location 0x00000000.
I have tried to dynamically allocate memory and it gives the same error. What I am doing wrong?
The last update of the code:
#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]);
}
}
Upvotes: 4
Views: 162
Reputation: 23699
You are not allocating the first dimension, ie a is a null pointer when you are trying to dereference it.
#include <stdlib.h>
a = malloc(number * sizeof *a);
BTW, sizeof(int)
is not sufficient 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 a whole correct code (although not perfect, as long as a
is an hugly 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);
}
Upvotes: 1
Reputation: 14039
You need to allocate memory for a
Before the for loop
a = (int **)malloc(number * sizeof(int *))
Upvotes: 5