slowr
slowr

Reputation: 54

malloc a char[][]

I am trying to malloc a char to have rows and columns with one letter in each cell. Something similar to int x[i][j] where I have i*rows and j*columns. Basically I want to make this:

     |     
     1
    222
   33333
  4444444

I tried with this code but it gives me an error: assignment makes an integer from pointer without a cast

A=(char**) malloc (5*sizeof(char*));
for(i=0;i<N+2;i++)`{
    A[i]=(char*) malloc(7*sizeof(char));
}
for(i=0;i<3;i++){
    for(j=0;j<7;j++){
       left=3;
       right=3;
       if((j>=left)&&(j<=right)){
          A[i][j]=i;
       }
    }
    left--;
    right++;
}

Upvotes: 0

Views: 377

Answers (2)

Andrejs Cainikovs
Andrejs Cainikovs

Reputation: 28434

I would go with different approach:

#define STEPS      5
#define ARRAY_SIZE STEPS*STEPS

The size of the array in your case can be easily calculated by the formula above.
Now, you just need to allocate fixed size of bytes, and fill it. That's it. Even more, the version below will simply out-beat your version in simplicity and performance.

int i, j;
char *array;

array = malloc(ARRAY_SIZE);
for (i = 0; i < STEPS; i++)
    for (j = 0; j < (i * 2 + 1); j++)
        *(array + i * STEPS + j) = i + 1;

Proof.

Upvotes: 3

Max Horn
Max Horn

Reputation: 572

This compiles fine for me, as long as I add this around your code snippet; note that "A" was declared as being of type "char **". It won't work if you write, say "char A[][]".

#include <stdlib.h>

int main() {
  const int N = 10;
  int i, j, left, right;
  char **A;
  /* your code */
  return 0;
}

Upvotes: 1

Related Questions