how do you intialise a 2D array?
int array[][] ??
how do we use a 2D array as a parameter in function?
void functionName(int array[][] , int numRows , int numCols)
or
void functionName(int array[numRows][numCols])
??
please help
Printable View
how do you intialise a 2D array?
int array[][] ??
how do we use a 2D array as a parameter in function?
void functionName(int array[][] , int numRows , int numCols)
or
void functionName(int array[numRows][numCols])
??
please help
This works fine:
Code:#include <stdio.h>
#include <conio.h>
const int Width=5;
const int Height=8;
int MyArray[Width][Height]={0};
void Func(int Array[Width][Height])
{
Array[0][0]=12345;
}
int main()
{
Func(MyArray);
printf("%d", MyArray[0][0]);
getch();
}
const int Width=5;
const int Height=8;
int MyArray[Width][Height]={0};
so instead of defining the width and height ourselves
can we have user define it through scanf ?
Yes, but not in this way. We must use dynamic allocation (new or malloc).Quote:
Originally posted by Unregistered
so instead of defining the width and height ourselves
can we have user define it through scanf ?
Sample (creates an int array with 10 elements):
Code:int NrOfElements=10; //You can make the user input this number
int* Pointer;
Pointer = new int[NrOfElements]; //Allocate memory
if(Pointer!=NULL) //Check to see if allocation was successful
{
//Do whatever you want here
...
delete[] Pointer; //You must free the memory before you quit, memory leaks will occur otherwise
}
'new' and 'delete' are C++ keywords and they have no function in C. What you would want to do in C is this:Quote:
Originally posted by Magos
Yes, but not in this way. We must use dynamic allocation (new or malloc).
Sample (creates an int array with 10 elements):
Code:int NrOfElements=10; //You can make the user input this number
int* Pointer;
Pointer = new int[NrOfElements]; //Allocate memory
if(Pointer!=NULL) //Check to see if allocation was successful
{
//Do whatever you want here
...
delete[] Pointer; //You must free the memory before you quit, memory leaks will occur otherwise
}
Quzah.Code:char **new2DCharArray( int x, int y )
{
char **c = NULL;
if( x > 0 && y > 0 ) c = malloc( x * y * sizeof( char ) );
return c;
}
Oops, this is the C forum, right :rolleyes:Quote:
Originally posted by quzah
'new' and 'delete' are C++ keywords and they have no function in C. What you would want to do in C is this:
Quzah.
My mistake... :cool: