0

this code should create an array in main and then print it but every time I run it I just get an array of all 0s

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

void print(float **A, int w, int h){
  int i, j;

  A = (float*) malloc(w*h*sizeof(float));

  for (i=0;i<h;i++){
    A[i] = (float*) malloc(w*sizeof(float));
  }

  for (i=0; i<h; i++){
    for(j=0; j<w; j++){
      printf("%f ", A[i][j]);
    }

    printf("\n");
  }
}

int main(void) {

    int i;
    int x_dimension=3;
    int y_dimension=2;
    float arr [3][2]={};
    arr[0][0]=16.2;

    print(arr,x_dimension,y_dimension);

    return 0;
}
Whoami
  • 13,930
  • 19
  • 84
  • 140
user38085
  • 3
  • 1

2 Answers2

0

You're re-allocing it in your print function, this should work:

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

void print(float * A,int h, int w){
  int i,j;
  for (i=0;i<h;i++){
    for(j=0;j<w;j++){
      printf("%f ",A[i * w + j]);
    }
    printf("\n");
  }
}

int main(void) {
    int i;
    const int x_dimension=3;
    const int y_dimension=2;
    float arr[x_dimension][y_dimension];
    arr[0][0]=16.2;
    print(arr,x_dimension,y_dimension);
    return 0;
}

Note that I also inverted the w and h parameters in the print function.

jlhonora
  • 10,179
  • 10
  • 46
  • 70
0

I think you see the arr is not initialized:

  1. alloc memory?
  2. default values.
  3. float arr[][] is not same with float **arr, you should use like this: float (*A)[2]

But in your main function, you have finished the alloc work. The arr is allocated at the stack. So in your print function, what you have to do is only print the result or initialize each item's value.

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

void printArr(float (*A)[2],int w, int h){
    int i,j;
    //Wrong, A has been alloced.
    /*
       A = (float*) malloc(w*h*sizeof(float));
       for (i=0;i<h;i++){
       A[i]=(float*) malloc(w*sizeof(float));
       }
       */
    for (i=0;i<h;i++){
        for(j=0;j<w;j++){
            printf("%f ",A[i][j]);
        }
        printf("\n");
    }
}

void printPointer(float *A,int w, int h){
    int i,j;
    //Wrong, A has been alloced.
    /*
       A = (float*) malloc(w*h*sizeof(float));
       for (i=0;i<h;i++){
       A[i]=(float*) malloc(w*sizeof(float));
       }
       */
    for (i=0;i<h;i++){
        for(j=0;j<w;j++){
            printf("%f ",*((A+i*h)+j));
        }
        printf("\n");
    }
}
int main(void) {
    int x_dimension=3;
    int y_dimension=2;

    //By Array, Array is not a pointer, but is a structure
    float arr[2][3] = {};
    //Only [0][0] item has been initialized
    arr[0][0]=16.2f;
    printArr(arr,x_dimension,y_dimension);

    //By pointer
    float* arrp = (float*)calloc(x_dimension*y_dimension,sizeof(float));
    *arrp=16.2f;
    printPointer(arrp,x_dimension,y_dimension);


    return 0;
}
QJGui
  • 907
  • 8
  • 10