Apologies if this is a "basic" question, but I am new to C and can't find the answer. My question is regarding the need to malloc
a variable and return its pointer within a function, compared with creating the variable within the function and return
ing the result.
The first issue that comes to mind is that any variables declared within the scope of the function will be destroyed once the function terminates; so why is it then that the following is valid:
int add(int a, int b)
{
int result;
result = a + b;
return result;
}
But the following is not?
char *concat(char* a, char* b)
{
char result[10];
strcat(result, a);
strcat(result, b);
return result;
}
The warning you get is that you are returning an address to a local variable, but this is what we are also doing in the first function? Does the behaviour differ depending on the type?
For a more real example, I'm very confused regarding which of the following 2 functions I should be using, as they both work perfectly well for my program:
struct Card *card_create(enum Rank rank, enum Suit suit)
{
struct Card *card = malloc(sizeof(struct Card));
if(card == NULL) {
fprintf(stderr, "malloc: %s", strerror(errno));
return NULL;
}
card->rank = rank;
card->suit = suit;
return card;
}
Or:
struct Card card_create(enum Rank rank, enum Suit suit)
{
struct Card card;
card.rank = rank;
card.suit = suit;
return card;
}
Again, sorry if this is a nooby question, but I'd really appreciate an explanation. Thanks!