Need some help breaking down this C function. I'm stuck on the malloc line. I do not understand what the "+8" is doing and/or why it is even there. My research revealed it has something to do with address arithmetic. Also, I won't mind some help checking the rest of my breakdown (comments) of each line of code is correct.
// Prints help message to the console
// Returns a string
char * helloWorld(char * name) { //The * is a pointer to an address. (char * name) = the address to a char pointer stored/passed via name.
char * answer = malloc(strlen(name) + 8); //syntax = (cast-type*) malloc(byte-size); answer has a * because malloc returns a void pointer. The * deferences the pointer
//and tells the program to use the value at that member address.
//strlen returns a
printf("This prints to the console when you Run Tests");
strcpy(answer, "Hello, "); //This returns a pointer to the destination string dest. char *strcpy(char *dest, const char *src)
//(answer {dest}, "Hello, "{string to be copied to dest}) *dest= The value at the pointer of src("Hello, ") will be assigned.
strcat(answer {des}, name {src}); //char *strcat(char *dest, const char *src) --> appends the string pointed to by src to the end of the string pointed to by dest.
return answer; //adds name to the end of answer. -->Hello, name.
}
It is supposed that the fucntion must return a string like for example
"Hello, N6DYN"
where the name "N6DYN" is passed to the function through the parameter name.
So the magic number 8 means the size of the string "Hello, "
that is stored in memory like
{ 'H', 'e', 'l', 'l', 'o', ',', ' ', '\0' }
The function can be declared and defined the following way as it is shown in the demonstration program below
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * helloWorld( const char * name )
{
const char *hello = "Hello, ";
char *answer = malloc( strlen( name ) + strlen( hello ) + 1 );
if ( answer != NULL )
{
strcpy( answer, hello );
strcat( answer, name );
}
return answer;
}
int main( void )
{
char name[100] = "";
printf( "Enter your name: " );
scanf( "%99s", name );
char *hello = helloWorld( name );
if ( hello != NULL ) puts( hello );
free( hello );
}
Instead of these lines within the function
const char *hello = "Hello, ";
char *answer = malloc( strlen( name ) + strlen( hello ) + 1 );
you could also write
const char hello[] = "Hello, ";
char *answer = malloc( strlen( name ) + sizeof( hello ) );
that is in this case sizeof( hello )
is equal to 8
that is the same value if to write strlen( hello ) + 1
.