0

The dynamicRandomMatrix function should return a pointer to an array of n pointers each of which points to an array of n random integers.

I got it to print mostly correct, except the first number in the array. This is the output:

n=3: -2084546528, 59, 45

Can anyone help me figure out why the first number in the array is so small? I think it must be something to do with local variables and access or something, but I am not sure.

int** dynamicRandomMatrix(int n){
    int **ptr;
    ptr = malloc(sizeof(int) * n);
    for (int i = 0; i < n; i++) {
        int *address = randomArray(n);
        ptr[i] = address;
    }
    return ptr;
    free (ptr);
}

int* randomArray(int n){
    int *arr;
    arr = malloc(sizeof(int) * n);
    for (int i = 0; i < n; i++) {
        int num = (rand() % (100 - 1 + 1)) + 1;
        arr[i] = num;
    }
    return arr;
    free(arr);

}

int main(){
    int **ptr;
    int i;
    ptr = dynamicRandomMatrix(3);
    printf("n=3: ");
    for (i = 0; i < 3; i++) {
        printf("%d, ", *ptr[i]);
    }
    return 0;
}
1
  • Once you have this running, submit it at codereview.stackexchange.com. There are several things bad in your code. Commented Apr 9, 2020 at 5:45

1 Answer 1

2

In your code,

 ptr = malloc(sizeof(int) * n);

is not correct, each element in ptr array is expected to point to a int *, so it should be ptr = malloc(sizeof(int*) * n);. To avoid this, you can use the form:

ptr = malloc(sizeof(*ptr) * n);

That said, all your free(array); and free (ptr); are dead code, as upon encountering an unconditional return statement, code flow (execution) returns to the caller, and no further execution in that block (function) takes place. Your compiler should have warned about this issue. If not, use proper flags to enbale all warnings in your compiler settings.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.