Re: Compiler Warning



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

.



Relevant Pages

  • Re: help getting substring
    ... I need a program to extract a substring from the following pattern ... char* deangle ... What does deangle do when passed a string of the form ... char *deangle(char *str) ...
    (comp.lang.c)
  • Re: help needed regarding compiling 2 C files
    ... How to compile two .C files at once? ... In my program I am tring to fetch one string from the array "cmdbuffer ... int main(int argc,char *argv) ...
    (comp.lang.c)
  • Re: How to Return an array of strings in C (char**)
    ... If your code in the calling function really uses a char* that points ... to a literal string, change it to use an array. ... any user defined function or object name beginning with str. ... ptr is a char**. ...
    (comp.lang.c)
  • Text to string program
    ... This is a program to convert a text file to a C string. ... char *fnametoid; ... char *str; ... ch - an escaped character ...
    (comp.lang.c)
  • Re: Are _T() and TEXT() macros equivalent?
    ... on the compile guidelines). ... But we can already achieve that with TCHAR. ... With the meaning of char dependent on the capriciousness ... convey the idea of "string" very well. ...
    (microsoft.public.vc.mfc)