Returning string pointer from a function: Error
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdbool.h>
char** parser(char *message)
{
char a[9][256];
char* tmp =message;
bool inQuote=0;
int counter=0;
int counter2=0;
while(*tmp!='\0')
{
switch(*tmp)
{
case ',': if(!inQuote)
{
a[counter][counter2]='\0';
printf("A[%d]: %s\n",counter,a[counter]);
counter++;
counter2=0;
}
break;
case '"':
inQuote=!inQuote;
break;
default:
a[counter][counter2]=*tmp;
counter2++;
break;
}
tmp++;
}
a[counter][counter2]='\0';
printf("A[%d]: %s\n",counter,a[counter]);
return(a);
}
int main()
{
char **a = parser("N,8545,01/02/2011 09:15:01.815,\"RASTA OPTSTK 24FEB2011 1,150.00 CE\",开发者_如何学CS,8.80,250,0.00,0");
return 0;
}
The error given is at Line 38 : return from incompatible pointer type
and function returns address of local variable
EDIT Can somebody modify the code accordingly so that I can access (via pointer) the contents of 'a' from main();
The errors speak for themselves
Line 38 : return from incompatible pointer type
a has been defined as char a[9][256]
. So, in the statement return(a);
, the type of value being returned is char (*)[256]
( pointer to an array of 256 chars ) and not char **
( as per the prototype of parser() )
function returns address of local variable
Well, a is a variable local to the function. You should not be returning address of local variables ( unless memory for it has been dynamically allocated or it is a static variable )
It is not advisable to return the address of a local variable outside the function as they are stored in the the stack, and should not be accessed by outside the function. The incompatible type warning can be removed by proper typecasting - but again, you shouldn't return the address of local variable.
In your code you are returning pointer but in the function definition you have declared it to be returning pointer to pointer that is the reason why you are encountering error.Also since the local variables are created in stack and once the control returns to calling function stack is cleared thus you are referencing to a location which does not contain data.Thus it would be better to declare your 2D array of character to be static.
char** parser(char message) { char a[9][256]; char tmp =message; bool inQuote=0;
MUST be
char** parser(char message) { static char a[9][256]; char tmp =message; bool inQuote=0;
精彩评论