Home > Back-end >  problem passing dynamic array via function c
problem passing dynamic array via function c

Time:12-04

I have this kind of code

typedef struct {
    int x;
    int y;
} Test;

Test* getTest(int *length) {
    Test *toReturn = malloc(sizeof(Test));
    // Some operations with realloc
    return toReturn;
}

void printTest(Test *arrTest, int length) {
    for(int i = 0; i < length; i  ) {
        // Some operations
    }
}

int main() {
    int testlength = 0;
    Test *myTest = getTest(&testlength);
    printTest(myTest, testLength) // Gives random numbers
}

Don't know why it gives random numbers, when I'm in the main tho (the whole code) it does not give these kinds of errors

CodePudding user response:

Made minor changes to the code, see below:

#include <stdio.h>

typedef struct {
    int x;
    int y;
} Test;

Test* getTest(int *length) {
    Test *toReturn = (Test *)malloc(sizeof(Test));
    // Some operations with realloc
    return toReturn;
}

void printTest(Test *arrTest, int length) {
    printf("%d ", length);
    for(int i = 0; i < length; i  ) {
        // Some operations
    }
}

int main() {
    int tlen = 0;
    Test *myTest = getTest(&tlen);
    printTest(myTest, tlen); // Gives random numbers
    printf("....Exit....");
    return 0;
}

CodePudding user response:

It looks like you are encountering an issue with the way you are passing the length of the Test array to the printTest function. In the getTest function, you are using a pointer to an int variable to store the length of the array. However, in the main function, you are passing the value of this variable directly to the printTest function, rather than passing a pointer to the variable.

To fix this issue, you can change the printTest function to accept a pointer to the length variable, rather than the value of the length variable itself. This will allow you to pass the length of the array correctly and avoid getting random numbers in the output.

Here is an example of how you could make this change:

typedef struct {
    int x;
    int y;
} Test;

Test* getTest(int *length) {
    Test *toReturn = malloc(sizeof(Test));
    // Some operations with realloc
    return toReturn;
}

void printTest(Test *arrTest, int *length) {
    // Loop through the array and print the values
    for(int i = 0; i < *length; i  ) {
        printf("Test[%d]: x = %d, y = %d\n", i, arrTest[i].x, arrTest[i].y);
    }
}

int main() {
    int testlength = 0;
    Test *myTest = getTest(&testlength);
    // Pass a pointer to the testLength variable to the printTest function
    printTest(myTest, &testLength) // Should not give random numbers
}
  • Related