c - 2d arrays with pointers -


so have following code far:

#include <stdio.h>  int foo (int *pointer, int row, int col);   int main() {   int array[3][3] ={ {1,2,3},{4,5,6},{7,8,9}};    int *pointer= array[0];    int row = 2;    int col = 2;     int answer = foo (pointer, row, col);     printf("%d", answer); //prints 5 (which wrong)   printf("%d", array[2][2]); //prints 9 }  int foo (int *pointer, int row, int col){ //i don't want use square brackets here, unless have to.    int value;    value = *((int *)(pointer+row)+col);   return value;  } 

so main issue passing 2d pointer, please explain in detail still new @ coding. don't want change passing (as in want use pointer in foo(pointer, row, col) , not foo (array, row, col).

passing 2d pointer

from how (ab)used terminology, it's quite clear you're under wrong impression pointers , arrays same. they aren't.

if want access multidimensional array using pointers, must specify dimensions (except first, innermost one) , use pointer arithmetic correctly, possibly using pointers-to-array, since multidimensional arrays contiguous in memory:

const size_t h = 2; const size_t w = 3; int arr[h][w] = {     { 1, 2, 3 },     { 4, 5, 6 } };  int *p = &arr[1][2]; int *q = arr[1]; int (*t)[3] = &arr[1]; printf("arr[1][2] == %d == %d == %d\n", *p, q[2], (*t)[2]);  return 0; 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -