Spoiler: I am an absolute beginner to C. I quickly threw threw together this program to test my knowledge, but my compiler is giving me errors. What is the problem and 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; i < length; i++)
{
temp[i] = string[i+start];
}
return temp;
}
EDIT:
Sorry, it’s like 1 AM here, I’ve been up trying to figure this out.
The errors are:
main.c: In function ‘main’:
main.c:9: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘int’
main.c: At top level:
main.c:12: error: conflicting types for ‘substr’
Here are the errors I see:
Use of uninitialized pointer
In
substryou declarechar *temp;and then use it without initializing it to anything. This is not a compile-time error, but this program will almost certainly crash when you run it, sincetempwill effectively point to a random memory address. This is a case of undefined behavior, and C is chock full of it. Undefined behavior will come out of nowhere and eat your pets if you aren’t careful.Consider
malloc()ing some memory, or having your function receive a pointer to a buffer where it can write the portion of the string.Use of function not yet declared
In C you must declare functions before they are used, or at least declare their prototype. Above
main()‘s declaration, add this line:No use of
constwhere it makes senseWhen assigning a string literal to a
char*, that variable should be declaredconst. So changeto
You will have to change your function prototype to
which is what it should have been in the first place.
Added 2010-12-02:
substr()does not add terminating null characterThe
substr()function, while algorithmically correct in every other sense, does not add a terminating null character to the new string. This will causeprintf()and every other string-using function (likestrlen(),strcpy(), etc.) to run off the end of the string into unallocated heap memory, or stack memory (depending on how you resolve the “uninitialized pointer” issue).To fix this, add this line immediately after the
forloop, and before thereturnstatement:Note that this should not be added in the for loop, as that would have the effect of creating a string with zero length.