I think my function is returning NULL since I initilize it to it. But I get compiling error if I dont.
This is just a prototype that I made in a test.c file to test it. So when I get it to work I will copy back the lookup function back into the correct file.
This is part of pset6 of cs50 if that helps anyone.
const char* lookup(const char* extension);
int main(void)
{
const char* type = "css";
const char* ending = lookup(type);
printf("the exstension: %s\nis of type = %s\n", type, ending);
}
const char* lookup(const char* extension)
{
char temp[strlen(extension)];
for (int i = 0; i < strlen(temp); i++)
{
if (isalpha(extension[i]))
temp[i] = tolower(extension[i]);
}
printf("temp = %s\n", temp);
char* filetype = NULL;
if (strcmp(temp, "html") == 0)
strcpy(filetype, "text/html");
else if(strcmp(temp, "css") == 0)
strcpy(filetype, "text/css");
else if(strcmp(temp, "js") == 0)
strcpy(filetype, "text/js");
else if(strcmp(temp, "jpg") == 0)
strcpy(filetype, "image/jpg");
else if(strcmp(temp, "ico" ) == 0)
strcpy(filetype, "image/x-icon");
else if(strcmp(temp, "gif") == 0)
strcpy(filetype, "image/gif");
else if(strcmp(temp, "png") == 0)
strcpy(filetype, "image/png");
else
return NULL;
return filetype;
}
I'm using all the correct libraries, it screwed up my code preview when I tried to include them!
char temp[strlen(extension)];
You don't reserve the space for the trailing null character and you never set it! For example, char temp[strlen(extension) + 1] = {0};.
Then:
char* filetype = NULL;
if (strcmp(temp, "html") == 0)
strcpy(filetype, "text/html");
filetype pointed object must be allocated, for example using malloc, otherwise strcpy is copying with a null pointer.
Are you sure that extension contains only extension without .? I can prefer to use _stricmp, strcmpi to compare case insensitive. And why you do strcpy to filetype instead of assignment? You have only pointer without malloc:
const char* lookup(const char* extension)
{
const char* filetype = NULL;
if (_stricmp(extension, "html") == 0)
filetype = "text/html";
else if(_stricmp(extension, "css") == 0)
filetype = "text/css";
else if(_stricmp(extension, "js") == 0)
filetype = "text/js";
else if(_stricmp(extension, "jpg") == 0)
filetype = "image/jpg";
else if(_stricmp(extension, "ico" ) == 0)
filetype = "image/x-icon";
else if(_stricmp(extension, "gif") == 0)
filetype = "image/gif";
else if(_stricmp(extension, "png") == 0)
filetype = "image/png";
return filetype;
}
Or better:
const char* lookup(const char* extension)
{
char * ext[] = { "html", "text/html", "css", "text/css", "js", "text/js", "jpg", "image/jpg", NULL };
for ( int i = 0; ext[i]; i += 2 )
{
if ( !stricmp( extension, ext[i] ) )
return ext[i+1];
}
return NULL;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With