Hello All,
I'm working on a program to parse and interpret command strings for an embedded system, but the issue I'm having is much more basic than string manipulation. I made a function that dynamically allocates memory for a struct array, which I want to be passed back to the calling function. I isolated the code that was giving me the issue and simplified it to show everyone what I'm doing. Here is the code:
Code:
/* Parameter units of measure structure */
typedef enum{
UNIT_V, // Voltage
UNIT_A, // Amperes
UNIT_W, // Watts
UNIT_rad, // Radians
UNIT_deg, // Degrees
//... (more enums, clipped for simplicity)
}MeasurementUnits;
typedef struct{
ParameterUnit unit;
char* sValue;
float nValue;
}CmdParameter;
int main()
{
CmdParameter* parameters;
foo(parameters);
return 0;
}
int foo(CmdParameter* P)
{
P = (CmdParameter*)calloc(3, sizeof(CmdParameter*));
P[0].nValue = 3; // Attempt to assign a value to one of the elements;
return 1;
}
So in the main function, I create a blank pointer that I want the resulting struct's reference to be assigned to. I then call the foo function, dynamically allocate an array with three elements and then assign that pointer to the variable. I then attempt to assign a value to one of the elements.
This code compiles with a "'parameters' is used uninitialized in this function" warning but when I execute the code and check the value of element P[0].nValue inside the foo() function, the value never gets assigned to 3.
I'm assuming that the issue is related to pointer references but the solution is not obvious to me at the moment. If I initialize and dimension the array in the main function, it works fine, but in the real program, I have to be able to do it in the function. I'm sure there's something silly I'm missing here.
Any help greatly appreciated.
- Jason O