I'm working on the following homework problem:
Given the first name and last name as parameters, write the code of the function
createFBlink()
. The functions returns a facebook link which serves as an alternate email of the facebook user. The variable holding the facebook link should contain the minimum number of bytes required to store the string representing the facebook link. If there is no first name or last name, the function returnsNULL
.For example, if
firstname = tzuyu
andlastname = chou
, the facebook link ischou.tzuyu@facebook.com
.
(See the original problem statement here.)
I've been trying to return a string from createFBlink
into main
. I've tried multiple methods such as turning char into static but I keep getting errors that I don't understand because I don't have a lot of experience with C.
I've had the best luck with using malloc
, but I've come across a problem wherein if ever there are parameters to the function I'm sending from main, I end up with a crash after the input. Here's my code so far:
#include <string.h>
#include <conio.h.>
#include <stdio.h>
#include <stdlib.h>
char *createFBlink(char *firstname , char *lastname) ;
int main(void)
{
char firstname[24] , lastname[24], fblink[24] ;
printf("Enter first name: ");
scanf("%s", firstname);
firstname[strlen(firstname)] = '\0';
printf("\n Enter last name: ");
scanf("%s", lastname);
lastname[strlen(lastname)] = '\0';
*fblink = createFBlink(firstname, lastname);
if(*firstname == '\0'){
printf("no facebook link generated");
}else{
printf("%s", *fblink);
}
getch();
return 0;
}
char * createFBlink(char *firstname , char *lastname)
{
int check1 = strlen(firstname) , check2 = strlen(lastname), num = check1+check2;
char link = (char*) malloc(sizeof(char) * num);
if(check1 == 0 || check2 == 0){
*firstname = '\0' ;
}else{
strcat(*lastname, ".");
strcat(*lastname, firstname);
strcat(*lastname, "@facebook.com");
strcpy(link , *lastname);
return link;
}
}