I'm running the below code to store a 2D square matrix. The code reads each line, splits the elements by space and stores them to a respective cell of the matrix.
Input format:
The first line contains a single integer n, denoting the number of rows and columns in the matrix . The next lines denote the matrix 's rows, with each line containing space-separated integers describing the columns.
Sample Input/Input used to test:
5
11 2 4 2 3
4 5 6 -1 0
10 8 -12 8 7
1 2 4 -2 5
10 -2 1 0 2
Program:
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void printMatrix(int n, int **matrix){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
printf("%d ",matrix[i][j]);
}
printf("\n");
}
}
int main(){
int size,length;
int **matrix,j;
char *buff=malloc(1000),*token;
fgets(buff,1000,stdin);
sscanf(buff,"%d",&size);
matrix=malloc(sizeof(int)*size);
for(int i=0;i<size;i++){
//Allocating memory for all the cells in ith row
matrix[i]=malloc(sizeof(int)*size);
buff='\0';
buff=malloc(1000);
fgets(buff,1000,stdin);
length=strlen(buff);
if ((buff[length-1])=='\n'){
buff[length-1]='\0';
}
j=0;
token=strtok(buff," ");
while(token){
matrix[i][j]=atoi(token);
token=strtok(NULL," ");
j++;
}
printf("\n");
printMatrix(i+1,matrix);
}
return 0;
}
Recieved Output:
11
11 2
4 5
11 2 4
4 5 6
10 8 -12
11 2 4 2
4 5 6 -1
10 8 -12 8
1 2 4 -2
869149824 22073 4 2 3
4 5 6 -1 0
10 8 -12 8 7
1 2 4 -2 5
10 -2 1 0 2
However, after 4th iteration, I'm getting garbage values 869149824 22073. I don't understand how the 1st row is getting modified.
I understand I might be making a silly mistake but I've spent quite some time figuring out what's missing here.I'd appreciate any help.
I took the opportunity to edit and clean up your program, your problem with the garbage prints were as previously stated caused by your memory management.
Here is the updated version of your program.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void printMatrix(int size, int i, int **matrix) {
printf("\n");
for (int y = 0; y <= i; y++) {
for (int x = 0; x < size; x++) {
printf("%d ", matrix[y][x]);
}
printf("\n");
}
}
int main() {
setvbuf(stdout, NULL, _IONBF, 0); // turn of buffering of stdout for debug.
int size;
int **matrix, j;
char buff[1000], *token;
fgets(buff, 1000, stdin);
buff[strcspn(buff, "\r\n")] = '\0';
sscanf(buff, "%d", &size);
// allocate matrix
matrix = malloc(sizeof(int*) * size);
for (int i = 0; i < size; i++) {
matrix[i] = malloc(sizeof(int) * size);
}
for (int i = 0; i < size; i++) {
fgets(buff, 1000, stdin);
buff[strcspn(buff, "\r\n")] = '\0';
j = 0;
token = strtok(buff, " ");
while (token) {
matrix[i][j] = atoi(token);
token = strtok(NULL, " ");
j++;
}
printMatrix(size, i, matrix);
}
return 0;
}
The major differences are:
buff