Integral value implicitly converted to pointer in assignment

showbix
showbix used Ask the Experts™
on
What's wrong with this program?

#include <stdio.h>

int main(int argc, char *argv[])
{
     char some_str[50];
     
     strncpy(some_str," ABCDEFGHI JKL ");    
    char *result = trim_whitespace(some_str);
    printf("result = %s\n", result);
    free(result);
     
     return 0;
}

char * trim_whitespace (char * str)
{
    char *whitespace = " \t\v\r\n";
    size_t start = strspn(str, whitespace);
    size_t end = start + 1;
    size_t needed_size = 0;
    char * result = NULL;

     while (!isspace(str[end]))
     {
         ++end;
    }
    needed_size = end - start;
    result = malloc(needed_size+1);
    strncpy (result, &str[start], needed_size);
    return result;
}

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
1. In main, declaration of 'result' is after call to strcpy, which is not acceptable in C. Every variable should be declared at the start of statement block.

2. As 'trim_whitespace' is not declared before its use, compiler assumes it as function returning integer value.
To do away with this, add a line

char * trim_whitespace (char * str);

before 'main' function.

-Rohan
obg

Commented:
The result of strncpy is NOT nul terminated unless you have no WS in the end. End trim_whitespace with result[needed_size] = '\0';
CEO/Programmer
Commented:
Well it was my code and
1) to nrohand a declaration after some lines of code is perfeclty ok with ISO/ANSI C99, A lot of compilers to not comply to it among them are Visual C/C++

2) if you do not want to write a prototyp section than one has to place if in front of any function which calls it

to obg
You are fully correct, I thougth about it after I tried to make a more elegant solution. And posted it to
http://www.experts-exchange.com/Programming/Programming_Languages/C/Q_20399002.html

Regards
Friedrich
fridomCEO/Programmer

Commented:
Forget a thing to showbix, You must include the appropriate headers! They were in my code for a reason

Regards
Friedrich

Commented:
..and the obvious error: strncpy takes 3 arguments.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial