![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: Jan 2005
Posts: 3
Rep Power: 0
![]() |
To Dizzutch
Dizzutch,
Hi! Thanks for replying me in "Read and print a square matrix". But I have tried your suggestion and errors came out. I inputted #include <iostream.h> #include <stdlib.h> void main() { int i,j,N; cout<<"Enter N:"; cin>>N; for(i=0;i<N;i++) for(j=0;j<N;j++) int array[i][j]=(int)malloc(sizeof(int)); } |
|
|
|
|
|
#2 |
|
Professional Programmer
|
was the error during compile time or during run time? and what is the error? I'm not that good with C++, but the syntax looks correct for ANSII C.
|
|
|
|
|
|
#3 |
|
Programmer
Join Date: Dec 2004
Posts: 35
Rep Power: 0
![]() |
>void main()
int main(). A void return value has never been correct C or C++. >int array[i][j]=(int)malloc(sizeof(int)); This will fail to work for quite a few reasons. First, arrays must have a constant size in C++, variables won't work. Second, malloc returns a pointer yet you cast it to int. Third, array isn't a valid lvalue and thus cannot be assigned the return value of malloc, even if you do cast it to int. Here is the correct C++ code to do what you want (using malloc): #include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int N;
int **array;
cout<<"Enter N: ";
cin>> N;
// Create
array = (int **)malloc(N * sizeof *array);
for (int i = 0; i < N; i++)
array[i] = (int *)malloc(N * sizeof *array[i]);
// Initialize
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
array[i][j] = i * j;
}
// Display
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
cout<< array[i][j] <<'\t';
cout<<endl;
}
// Destroy
for (int i = 0; i < N; i++)
free(array[i]);
free(array);
}#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int N;
int **array;
cout<<"Enter N: ";
cin>> N;
// Create
array = new int*[N];
for (int i = 0; i < N; i++)
array[i] = new int[N];
// Initialize
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
array[i][j] = i * j;
}
// Display
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
cout<< array[i][j] <<'\t';
cout<<endl;
}
// Destroy
for (int i = 0; i < N; i++)
delete [] array[i];
delete [] array;
}#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;
int main()
{
int N;
cout<<"Enter N: ";
cin>> N;
vector< vector<int> > array(N, vector<int>(N));
// Initialize
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
array[i][j] = i * j;
}
// Display
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
cout<< array[i][j] <<'\t';
cout<<endl;
}
} |
|
|
|
|
|
#4 |
|
Professional Programmer
|
sorry, i wrote that on a limb, didn't really test it.
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|