Before anything else, please note that in your example, if temp is to be used as a cstring you should define it with room for 11 chars: those 10 you initialize it with + 1 for the terminating '\0'.
If you intend to use it as a plain char array, consider defining it explicitly...
Code:
char temp[10] = {
'5', '4', '3', '2', '1', 'A', 'C', 'F', 'E', 'B'
};
and refrain from passing it to functions that expect cstrings (that is, all standard C string functions).
Originally Posted by
nime
@Andi, I already get satisfied answer in first two replies to my question what mean that question is formed correctly.
I practic situation my char array (temp) is readen from binary file and behind it is defined data structure with various datatypes so I have to post much of non relevant code which involve gui stuff, database stuff, charactersets conversion stuff and other...
If you want to see a goal you don't have to see whole match.
@migf1, no, temp is not known in the caller. So whe have to go to getstatus to get an important part of temp (one char in this case).
So I guess, getstatus() generates locally a cstring temp and you need to save in caller's context some part of temp starting at bd, right?
If so, then the solution given in post #2 doesn't seem suitable, since it assumes that temp is known to the caller, who passes it to the function.
Now, if you only need to return to the caller the bd-th character of temp, then there is no need for the function to return a char pointer, and the solution given in post #3 should be sufficient.
On the other hand, if you need to return to the caller the substring of temp that starts at position bd (which would make more sense, given the signature of getstatus()) you should allocate room for the substring inside the function, copy &temp[bd] into it and return it. In this case, you should free() the returned substring in caller's context, when done using it.
Here's a possible implementation, assuming temp is a plain char array and not a cstring...
Code:
char *getstatus( int bd )
{
char *ret = NULL;
char temp[10] = { '5', '4', '3', '2', '1', 'A', 'C', 'F', 'E', 'B' };
size_t sz = 10 - bd;
if ( sz < 1 || sz > 10 )
return NULL;
ret = malloc( sz /* * sizeof(char) */ );
if ( !ret )
return NULL;
memcpy( ret, &temp[bd], sz);
return ret;
}
Then in the caller...
Code:
int main( void )
{
char *gs = getstatus(5);
if ( !gs ) {
/* getstatus() failed, handle error here */
}
else {
/* do whatever you need to do with gs here, then... */
free( gs );
gs = NULL;
}
...