Alex G.P. Alex G.P. - 10 days ago 5
C Question

ANSI C work with 2dim array throught pointers

Long long time ago I've played with

C
a lot but forgot everything. Now I am trying to solve easy tasks and failed.

I'd like to write function which takes 2dim array or
char*
and print it. but my code is buggy and I do not understand why. As I understand
products
is pointer to 2dim array, so increasing it to
i * sizeof(char**)
I get pointer to sub-array, and increasing that sub-array pointer I get pointer to char block. But it seems that my code looking to different memory block.

About
products
array - I know that it has N rows and 2 columns.

#include <stdio.h>
#include <string.h>

void print(char*** products, size_t rows, size_t cols) {
size_t i;

for(i = 0; i < rows; i++) {
printf("Col1: '%s. Col2: %s'\n",
(products + i * sizeof(char**)),
(products + i * sizeof(char**) + sizeof(char*))
);
}
}

int main(void) {
const char* a[][3] = {{"abc", "1"}, {"def", "2"}, {"ghi", "3"}};
print((char***)a, 3, 2);

return 0;
}

Answer

You've mixed up what you regard as columns and rows. Fix that, then get rid of the three star nonsense, make the function accept variable amount of columns and you end up with this:

#include <stdio.h>

void print(size_t rows, size_t cols, const char* products[rows][cols]) 
{
  for(size_t r=0; r<rows; r++) 
  {
    for(size_t c=0; c<cols; c++)
    {
      printf("Col%zu: %s. ", c, products[r][c]);
    }
    printf("\n");
  }
}

int main (void) 
{
  const char* a[3][2] = {{"abc", "1"}, {"def", "2"}, {"ghi", "3"}};
  print(3, 2, a);

  return 0;
}

And that's that, no need to complicate this futher.

Comments