Reputation: 1545
I'm allocating memory for a 2D array I think I'm doing it good, but when I at the memory it seems to be different that what I wrote.
int size = 4;
table = (int**)malloc(size*sizeof(int*));
int i;
for (i = 0; i < size; i++)
{
table[i] = (int*)malloc(size*sizeof(int));
}
But when I look in the debugger, after I add all the elements of a 4X4 2D array. It seems like I have more than 4 columns. I just add int in a regular way
table[i][j] = num;
any help will be greatly appreciated!
Thank!
EDIT: code of adding the int
int lineCounter = 0;
char line[200];
while (fgets(line, 200, fr) != NULL)
{
i = 0;
char* split;
int num;
split = strtok(line, " ");
sscanf(split, "%d", &num);
table[lineCounter][i] = num;
i++;
for (i ; i < size; i++)
{
int num;
split = strtok(NULL, " ");
sscanf(split, "%d", &num);
table[lineCounter][i] = num;
}
lineCounter++;
}
Upvotes: 0
Views: 96
Reputation: 19864
Check the code below:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int j,i;
int **table;
int lineCounter = 0;
char line[200];
int size = 4;
table = (int**)malloc(size*sizeof(int*));
for (i = 0; i < size; i++)
{
table[i] = (int*)malloc(size*sizeof(int));
}
while (fgets(line, 200, stdin) != NULL)
{
i = 0;
char* split;
int num;
split = strtok(line, " ");
sscanf(split, "%d", &num);
table[lineCounter][i] = num;
i++;
for (; i < size; i++)
{
int num;
split = strtok(NULL, " ");
sscanf(split, "%d", &num);
table[lineCounter][i] = num;
}
lineCounter++;
}
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
printf("%d ",table[i][j]);
printf("\n");
}
return 0;
}
Upvotes: 1