0

I am trying to allocate the array from command line inputs in the following way.. but I am still getting warnings.. pasted the error message below.. please look into it.. what changes could make this code perfect..

int ni = atoi(argv[1]);
int nj = atoi(argv[2]);

int *a[ni][nj];

for(i=1; i<ni; i++)
{
    for(j=1; j<nj; j++)
    {
        a[i][j] = 10*j + i;
    }
    printf("%d", a[i][j]);
}

Compiler oputput:

In function main:
warning: incompatible implicit declaration of built-in function malloc
warning: assignment makes pointer from integer without a cast
nakiya
  • 14,063
  • 21
  • 79
  • 118
Deepak
  • 962
  • 4
  • 17
  • 38
  • Please add the complete warning message (With line, etc). And mention the compiler. – nakiya Feb 20 '14 at 03:19
  • 1
    Your code snippet doesn't contain `malloc`, so you aren't giving us the full story, but: `a` is an array of `int*`, you are treating it as an array of `int`. – John3136 Feb 20 '14 at 03:20
  • `std::vector> a(n1, std::vector(n2));` would get it much closer to perfect than what you have now, and its still dynamic. – WhozCraig Feb 20 '14 at 03:34

2 Answers2

3

Since you're using C++ I'd suggest the following way:

#include <vector>
#include <iostream>

    // ...

    int ni = atoi(argv[1]);
    int nj = atoi(argv[2]);

    std::vector< vector<int> > a(ni, vector<int>(nj));

    for (int i = 0; i<ni; i++)
    {
        for (int j = 0; j<nj; j++)
        {
            a[i][j] = 10 * j + i;
            std::cout << a[i][j];
        }       
    }   
jaho
  • 4,852
  • 6
  • 40
  • 66
0

You need to use dynamic allocation. You cannot do static allocation from command-line input.

Take a look here: How do I declare a 2d array in C++ using new?

Community
  • 1
  • 1