C Newbie: Help with Simple Function -
spoiler: absolute beginner c. threw threw program test knowledge, compiler giving me errors. problem , why?
#include <stdio.h> void main() { char *string = "abcdefghi"; printf("%s\n\n", string); printf("%s\n\n", substr(string, 1, 2)); } char * substr(char *string, int start, int length) { int i; char *temp; for(i = 0; < length; i++) { temp[i] = string[i+start]; } return temp; }
edit:
sorry, it's 1 here, i've been trying figure out.
the errors are:
main.c: in function ‘main’: main.c:9: warning: format ‘%s’ expects type ‘char *’, argument 2 has type ‘int’ main.c: @ top level: main.c:12: error: conflicting types ‘substr’
here errors see:
use of uninitialized pointer
in substr
declare char *temp;
, use without initializing anything. not compile-time error, program crash when run it, since temp
point random memory address. case of undefined behavior, , c chock full of it. undefined behavior come out of , eat pets if aren't careful.
consider malloc()
ing memory, or having function receive pointer buffer can write portion of string.
use of function not yet declared
in c must declare functions before used, or @ least declare prototype. above main()
's declaration, add line:
char * substr(char *string, int start, int length);
no use of const
makes sense
when assigning string literal char*
, variable should declared const
. change
char *string = "abcdefghi";
to
const char *string = "abcdefghi";
you have change function prototype to
char * substr(const char *string, int start, int length)
which should have been in first place.
added 2010-12-02:
substr()
not add terminating null character
the substr()
function, while algorithmically correct in every other sense, not add terminating null character new string. cause printf()
, every other string-using function (like strlen()
, strcpy()
, etc.) run off end of string unallocated heap memory, or stack memory (depending on how resolve "uninitialized pointer" issue).
to fix this, add line after for
loop, , before return
statement:
temp[i] = '\0';
note should not added in loop, have effect of creating string 0 length.
Comments
Post a Comment