| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
2D Array Problem...
Hey,
I basically wish to write a function which will accept a pointer (or a pointer to a pointer) and two integers (r and c). The same should display the arr[r][c]th element of the array where the pointer is pointing. Here is what i have done but the same throws a 'segmentation fault'. Please guide. #include<stdio.h> void disp(int **a,int r,int c) { printf("%d",a[r][c]); } int main() { int arr[3][2]={1,2,3,4,5,6}; disp(arr,1,2); return 0; } Thanks Neville |
|
#2
|
|||
|
|||
|
Hey Nevillemehta!
Check the main! You're declaring a two dimensional array, but initializing a one dimensional array!! I don't know if that's allowed, but still, you're asking for a value that doesn't exist (memory not reserved and that's why you get a segmentation fault!). Quote:
give it a try with this: int arr[3][2]={{1,2},{3,4},{5,6}}; and ask for arr[1][1] --> I'm a little rusty, but I think that prints out "2" Good Luck! Anibal. |
|
#3
|
|||
|
|||
|
I second to what Anibal suggested.He is correct in pointing out the mistake.
A two dimensional array is initialized as { {a,b}, {c,d} } |
|
#4
|
|||
|
|||
|
#include <stdio.h>
#include <stdlib.h> #define MAXLENGTH 5 void disp(int *a,int r,int c) { printf("%d",a[r * MAXLENGTH + c]); } int main() { int arr[3][MAXLENGTH] ={{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}}; disp((int *)arr, 1, 2); system("PAUSE"); return 0; } |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > 2D Array Problem... |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|
|