Reputation:
I'm trying to make a ADT, but when I created a function that return char type, the program is not working. This is the ADT:
typedef struct{
int ID;
char Writer[100];
char Title[100];
long Year;
}Book;
the function is:
char GetTitle(Book B){
return B.Title;
}
I used this to get the return value of the function:
printf("%s",GetTitle(B));
How do I return Char type?
Upvotes: 0
Views: 1353
Reputation: 16876
char* GetTitle(Book *B){
return B->Title;
}
Note that this is just returning a pointer to the title of the book. So when the book is destroyed, the pointer becomes invalid. You can't return the whole title, as you can't return an array. If you want to make a copy of the string after you got the pointer (so it stays valid after destroying the book), use strdup
:
Book* B = malloc(sizeof(Book));
// [...] initialize the book...
char *title = strdup(GetTitle(B));
free(B);
printf("%s",title);
free(title);
Edit: if strdup
is not available, check this answer for an implementation.
Upvotes: 3
Reputation: 1724
You absolutely must read warnings passed by the compiler: for sure it is telling you can't return an address from the stack of a function. It works by mere chance, as that memory is not valid after the function returns. You must proceed using pointers and references. Try changing char GetTitle(Book B);
to char* GetTitle(Book *B);
, like this:
#include <string.h>
#include <stdio.h>
typedef struct {
int ID;
char Writer[100];
char Title[100];
long Year;
} Book;
char* GetTitle(Book *B) {
return B->Title;
}
int main() {
Book B;
strcpy(B.Title, "Title");
printf("%s\n", GetTitle(&B));
return 0;
}
Upvotes: 1