can any1 help me regarding "passing multidimensional arrays"?
i have a dynamic array and i have to fill it with random values............. so i have to do smthin like randomAssign(&array,size) void randomAssign(int ***array,int size) { int i,j; for(i=1...size) for(j=1...size) array[i][j]=rand(); return; } but this gives a segmentation fault? so wer did i go wrong?
@nick67 @slotema
array is of type int ** int **array; array = builder(size); and my builder function is here int ** builder(int n) { int i; int *array=malloc(n*sizeof(int)); for(i=0;i<n;i++) array[i]=(int *)malloc(n*sizeof(int)); return array; } language s c
@ktobah
You know when you want to pass an Array as argument, don't use &, because C/C++ consider arrays as addresses. Try this .
nope tried that.............it dint work
any ideas?
I really don't have any idea, sorry.
tsk thanks nyway.......
You're welcome.
@A.Avinash_Goutham try something like this (with this example you have a 10x10 array with random values up to 99: #include <iostream> #include <ctime> #include <cstdlib> using namespace std; #define ARRAY_SIZE 10 void randomAssign(int *array_ptr,int size) { int i,j; srand ( time(NULL) ); for(i=0;i<size;i++) for(j=0;j<size;j++) { *array_ptr = rand() % 100; array_ptr++; } return; } int main() { int array[ARRAY_SIZE][ARRAY_SIZE]; randomAssign(&array[0][0], ARRAY_SIZE); return 0; }
Sir, the array should be dynamic...........i shud be able to give the size at the run time.....
main() { int n,i,j; printf("enter the size of the maze:"); scanf("%d",&n); static int **array; array=builder(n); if(array) { printf("array creation succesfull\n"); } printf("%d\n",rand()); assign(array,n); randomAssign(array,n); print(array,n); } int ** builder(int n) { int i; int *array=malloc(n*sizeof(int)); for(i=0;i<n;i++) array[i]=(int *)malloc(n*sizeof(int)); return array; } void print(int **array,int n) { int i,j; for(i=0;i<n;i++) { for(j=0;j<n;j++) printf("%d ",array[i,j]); printf("\n"); } return; } void assign(int **array,int n) { int i,j; for(i=0;i<n;i++) for(j=0;j<n;j++) { printf("enter element array[%d][%d]:",i,j); scanf("%d",&array[i][j]); } return; } void randomAssign(int **array,int n) { int i,j; for(i=0;i<n;i++) for(j=0;j<n;j++) array[i][j]=rand()%2; return; }
that was my code..
Join our real-time social learning platform and learn together with your friends!