Hi,I have tried to get this program to work,but it works to the moment when you enter some of the array`s numbers and then crashes.In different sizes of the matrix you can enter different number of numbers,but for instance when the matrix is 5x5 the program crashes after the 11th number,if the matrix is 9x9 crashes after 18th, if the matrix is 4x5 crashes after the 11th ,and 5x4 on the 9th.I think I have made the "for" loops right and I hope the problem is that I don`t know something rather than a stupid mistake.
I would love to recieve any help.

#include <iostream.h>
#include <stdio.h>

int** matrij;

void matrin(int i,int j)//Can I replace i and j with rows and cols here?
{
    cout<<"Enter the matrix number by number.\n"; 
    int a,b;
    for(a=0;a<i;a++)
     for(b=0;b<j;b++)
      scanf("%d",&matrij[a][b]);
}

void matrout(int i,int j)
{
    int a,b;
    for(a=0;a<i;a++){
     for(b=0;b<j;b++)
      printf("%d ",matrij[a][b]);
      cout<<"\n";
      }
}     

main()
{
      
      int cols,rows;
      cout<<"MATRIX V0.1\n";
      cout<<"Enter the number of rows and then the number of columns of the matrix.\n";
      cin>>rows>>cols;
      matrij=new int*[cols*rows];
      matrin(rows,cols);
      matrout(rows,cols);
      delete[] matrij;
      matrij=0;
      system("pause");
      return 0;
}

Recommended Answers

All 3 Replies

That's C++, not C, so I can't help you. Obviously, you're not allocating the memory you need.

When you can put in ten int's or so before the program crashes - that's an allocation that never worked.

You should be able to test and see if the call to allocate the memory, succeeded or not.

Oh yes its in the wrong section.But your advice is right-the problem is indeed in the allocation,but i still cant fix it

I have modified my program to use only C and made some changes to the pointer indexing.
It turns out that the problem was in this row
scanf("%d",&*(ptr+sizeof(int)*(j*a+b)));

#include <stdio.h>
#include <stdlib.h>

void matrin(int i,int j,int* ptr)//Can I replace i and j with rows and cols here?
{
    puts("Enter the matrix number by number.\n");
    int a,b;
    for(a=0;a<i;a++)
     for(b=0;b<j;b++)
      scanf("%d",&*(ptr+sizeof(int)*(j*a+b)));
}

void matrout(int i,int j,int* ptr)
{
    int a,b;
    for(a=0;a<i;a++){
     for(b=0;b<j;b++)
      printf("%d ",*(ptr+sizeof(int)*(j*a+b)));
      puts("\n");
      }
}     

main()
{
      int cols,rows,n;
      int* ptr;
      puts("MATRIX V0.1\n");
      puts("Enter the number of rows and then the number of columns of the matrix.\n");
      scanf("%d %d",&rows,&cols);
      int matrij[10][10];
      ptr=&matrij[0][0];
      matrin(rows,cols,ptr);
      matrout(rows,cols,ptr);
      system("pause");
      return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.