0

I'm trying to assign ith row values of 2d array to 1d array. Those arrays are created dynamically. My code is:

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

#define N 10
#define FRAC 10

int main(int argc, char *argv[]){

    int i, j;
    double **A, *B;

    A=(double**)malloc(sizeof(double)*N);
    for (i=0; i<N; i++){
        A[i]=(double*)malloc(sizeof(double)*N);
    }

    for (i=0; i<N; i++){
        for(j=0; j<N; j++){
            A[i][j]=i*j/FRAC;
        }
    }

    B=A[0];

    for(i=0; i<N; i++)
        printf("%f\n",B[i]);

    system("PAUSE");

    return 0;
}

When B is printed, all the values are shown as 0.0000. What is the problem here?

2 Answers 2

3

If you look at your loop:

for (i=0; i<N; i++){
    for(j=0; j<N; j++){
        A[i][j]=i*j/FRAC;
    }
}

You'll see that every element in A[0] involves a multiplication by i == 0 so the your B will be all zero.

If you assign B = A[1] and force the computation into floating point mode by defining FRAC to 10.0 (or by adding explicit casts), you'll see something more interesting from your printf loop.

And, while I'm here, please don't cast the return value from malloc, it is not necessary and it often hides mistakes. You're also not allocating A properly, you should be doing A = malloc(sizeof(double *) * N); lucky for you, double is almost always at least as big as a pointer.

This modified version of your program:

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

#define N 10
#define FRAC 10.0   /* CHANGED */

int main(int argc, char *argv[]) {
    int i, j;
    double **A, *B;

    A = malloc(sizeof(double *) * N);
    for(i = 0; i < N; i++) {
        A[i] = malloc(sizeof(double) * N);
    }

    for(i = 0; i < N; i++) {
        for(j = 0; j < N; j++) {
            /* This is floating point now that FRAC is 10.0 */
            A[i][j]= i * j / FRAC;
        }
    }

    B = A[1];   /* A[0] is all 0.0 so we'll look at A[1] instead. */
    for(i = 0; i < N; i++)
        printf("%f\n", B[i]);

    return 0;
}

Produce the following (which is more interesting and instructive than a bunch of zeros):

0.000000
0.100000
0.200000
0.300000
0.400000
0.500000
0.600000
0.700000
0.800000
0.900000
2
  • i am really embarrassed atm :) i tried to figure it out for hours. thank you sir!
    – onatm
    Apr 27, 2011 at 22:03
  • Thank you for your tips to allocate memory. I have to improve myself on memory management.
    – onatm
    Apr 27, 2011 at 22:13
1

Both i*j and FRAC are integers, and in C, dividing two integers results in an integer, discarding any decimals you would normally have.

Change FRAC to explicitly be a floating-point value, e.g. by using 10.0 instead of 10.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.