Re: Compiler Warning
- From: s0suk3@xxxxxxxxx
- Date: Mon, 1 Dec 2008 07:35:32 -0800 (PST)
On Dec 1, 8:55 am, srikar2097 <srikar2...@xxxxxxxxx> wrote:
I have written this small fn. to strip down whitespaces ("\n") a given
string (only leading and trailing).
The program itself might not be foolproof but that is not my concern
right now. When I compile this
I get a warning :--
"string_utils.c:96: warning: function returns address of local
variable.
I have declared the fn. as fn. pointer and this fn. returns the
address of a string array. Why does
the compiler give out this warning? Please help.
Try:
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
// Return value must be manually deallocated
char* xstrip(const char* str)
{
while (isspace((unsigned char) *str) && *str != '\0')
++str;
const char* end = str + strlen(str);
while ((isspace((unsigned char) *end) || *end == '\0') && end >
str)
--end;
char* buf = (char*) calloc(1, end - str + 2);
if (!buf)
return NULL;
strncpy(buf, str, end - str + 1);
return buf;
}
Or, if you want to modify the string in-place:
void xstrip(char* str)
{
char* start = str;
while (isspace((unsigned char) *start) && *start != '\0')
++start;
char* end = start + strlen(start);
while ((isspace((unsigned char) *end) || *end == '\0') && end >
start)
--end;
memmove((void*) str, (const void*) start, end - start + 1);
str[end - start + 1] = '\0';
}
Sebastian
.
- Follow-Ups:
- Re: Compiler Warning
- From: Ben Bacarisse
- Re: Compiler Warning
- From: Barry Schwarz
- Re: Compiler Warning
- References:
- Compiler Warning
- From: srikar2097
- Compiler Warning
- Prev by Date: Re: Sorry if it is not for this forum
- Next by Date: Re: Compiler Warning
- Previous by thread: Re: Compiler Warning
- Next by thread: Re: Compiler Warning
- Index(es):
Relevant Pages
|