Hi there,

Im trying to create a simple program that creates an 2D array of numbers and prints them to the screen via a function. I think i have got most of the way however, I cant seem to get the print function to print correctly. It's been a while since i coded in C. Can anyone see where i have slipped up?

#include <stdio.h>
#include <stdlib.h>

#define START        0
#define MAX          128

void printarray(int *,int);

int main(int argc, char *argv[])
{
  int i,j,c;
  int vig[MAX][MAX];
        
      for(i=0;i<MAX;i++)
        {
        c=START+i;            
           for(j=0;j<MAX;j++)
               {
                  if(c<MAX)        /* This section is a simple loop that initiates a Vigenère Table  */
                  {                /* into an array called "vig". This array will be used in the     */               
                  vig[i][j]=c;     /* encryption/decryption process later on.                        */
                  c++;              
                  }
                  else
                  {
                  c=START;   
                  vig[i][j]=c;
                  c++; 
                  }
              }                                         
        }
    
  
  printarray(&vig[0][0], MAX);
       
  system("PAUSE");  
  fclose(input);   	
  return 0;
}

void printarray(int *vig1,int n)
{
 int i,j,x;
 int vig2[MAX][MAX];
 
 vig1=&vig2[MAX][MAX];
       
  for(i=0;i<MAX;i++)                    
  {
        for(j=0;j<MAX;j++)
        {
        printf(" %d,",vig2[i][j]);
        } 
   printf(" \n");                  
  } 
   
}

Also I couldn't remember how to pass the array to the function without having to assign the pointer to a new array :

vig1=&vig2[MAX][MAX];

I didn't think you had to do this but cant get it to pass it in any other way.

Thanks for your time.

Craig

Dani AI

Generated

A quick summary and practical fixes for the array-passing confusion in this thread.

The core issue is type mismatch, not a printing bug. A true 2D array declared as int A[R][C] is laid out contiguously in row-major order and, when passed to a function, decays to a pointer to a row (type int (*)[C]), not to int **. That is why the compiler warns when you try to accept it as int **. As hinted and clarified, the function parameter must match the actual array type or you must treat the data differently (flat buffer or array-of-pointers).

A few safe approaches (C99/C11 and later variants shown where useful):

  • Pass as a VLA / pointer-to-array (keeps 2D indexing):
    
    void print_rows(int rows, int cols, const int arr[rows][cols]) { /* use arr[i][j] */ }

or

void print_rows(int rows, int cols, const int (arr)[cols]) { / use arr[i][j] */ }

Note: if you are compiling strictly C89, the column size must be a compile-time constant.

- Pass as a flat buffer (you already passed &A[0][0]; use linear indexing):

void print_flat(const int data, int rows, int cols) {
/
element (i,j) is data[icols + j] /
}


This matches a call that supplies `&A[0][0]`.

- Use `int **` only if you actually allocate an array-of-pointers (each row separately). In that case allocate each row with malloc and free them later; `int **` does not alias a contiguous `int[][]`.

Troubleshooting pointers seen in the original code:
- Do not reassign the incoming pointer to point at a new local 2D array; that discards the original data and is wrong.
- Match the prototype exactly to how you allocated/passed the array.
- Avoid nonportable calls like `system("PAUSE")` and remove calls to `fclose` on an unopened file.

Pick the approach that matches how the array is stored. For a simple fixed-size Vigenere table, passing the actual 2D array as `const int arr[rows][cols]` (or `const int (*arr)[cols]`) is the clearest and least error-prone.

Recommended Answers

All 5 Replies

>>void printarray(int *,int);
That is the wrong prototype because one star is a 1d array.

void printarray(int **,int);

or
void printarray(int *array[],int);

or
void printarray(int array[MAX][MAX],int);

My goodness... i feel foolish :)

Many thanks for that.. it jogged my memory

Craig

Ok new question on the same topic,

I'm now trying to make the print function generic so that instead of printing just one 2d array it could print any 2d array passed to it. (hope that makes sense)

I have amended the code and the function looks as follows:

void print2darray(int **vig1, int n)  /* function to print the array . 'n' is the array size */
{
 int i,j;
       
  for(i=0;i<n;i++)                    
  {
        for(j=0;j<n;j++)
        {
        printf(" %d,",vig1[i][j]);
        } 
   printf(" \n");                  
  } 
   
}

the function is defined as: void print2darray(int **,int); and is called as : print2darray(vig,MAX); the compiler does not like the calling line as states that it is an incompatible pointer type.

> void printarray(int **,int);
> void printarray(int *array[],int);
Neither of these are valid for passing a true 2D array.

void foo ( int **p ) {
}
void bar ( int *p[] ) {
}
void baz ( int p[][7] ) { // p[3][7] would also work
}
void qux ( int (*p)[7] ) {
}

int main() {
    int L[3][7];
    foo(L);
    bar(L);
    baz(L);
    qux(L);
    return 0;
}

$ gcc foo.c
foo.c: In function `main':
foo.c:12: warning: passing arg 1 of `foo' from incompatible pointer type
foo.c:13: warning: passing arg 1 of `bar' from incompatible pointer type

Thanks for that Salem :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.