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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments