Passing enumerations by reference...garbage value returned to main
I'm building a validation function for a particular enumeration data type. The validation function returns 0 (false) or 1 (true) if string passed is valid. At the same time, if the string is valid, then the enumeration subType is then populated with the correct entry.
As开发者_运维问答 the code is, it correctly populates subType in the function. I print the entry to the screen to check. But when I return to the main (see below), I get a garbage value (sometimes '11871397') when I print the string.
I've even tried this with or without declaring subType as const. I have a number of other validation functions written like this and they all handle the reference type correctly, which has led me to believe that it is an issue with the enumeration.
int val_subscriberType (char str[], const enum ns1__subscriberType *subType )
{
if (strcmp(upStr, "PREPAID") == 0)
{
enum ns1__subscriberType subType = ns1__subscriberType__prepaid;
printf("SubscriberFunction: %d \n", subType);
return 1;
}
else if (strcmp(upStr, "POSTPAID") == 0)
{
enum ns1__subscriberType subType = ns1__subscriberType__postpaid;
printf("SubscriberFunction: %d \n", subType);
return 1;
}
return 0;
}
Main
char *recRetTest = "aggressive";
enum ns1__recurrentRetrySchemaType recRet;
if ( val_recurrentRetrySchemaType (recRetTest, &recRet))
{
printf ("\nRecurrent Retry Schema main: %d \n", recRet);
}
P.S I've taken out the extra code where I convert the string to upper case etc.
Your main problem is that you're re-declaring subType
in the branches of the if
statement, which hides the parameter declaration; in short, you're assigning the value to a different object than the parameter.
Remove the const
in the parameter declaration, and rewrite the assignments as
if (strcmp(upStr, "PREPAID") == 0)
{
*subType = ns1__subscriberType__prepaid;
...
精彩评论