typedef struct Data* DATAS;
struct Data {
char *name;
char *city;
DATAS next;
};
typedef struct Data DATA;
int main(void){
DATAS tmp;
tmp=(DATAS) malloc(sizeof(DATA));
printf("please enter name:\n");
scanf("%s",&tmp->name);
printf("%s\n",&tmp->name);
printf("please enter city:\n");
scanf("%s",&tmp->city);
printf("%s\n",&tmp->name);
printf("%s\n",&tmp->city);
return 0;
}
This is part of a homework assignment. Or rather the concept is. I need to use ‘typedef struct Data* DATAS;’ which is throwing me off. When I run this I overwrite name with part of city so I get this as a result.
please enter name:
name
name
please enter city:
city
namecity
city
Any help would be great. Thanks. I’ve tried different variants of malloc using
tmp=(DATAS) malloc(sizeof(DATA));
tmp=(DATA) malloc(sizeof(DATA));
The best way to allocate a
struct Datais:Defining a typedef for a pointer type is not recommended (at least by me); using
struct Data *explicitly makes it clearer to the reader that you’re dealing with a pointer.Defining a typedef for a struct type is also unnecessary. A typedef simply declares a new name for an existing type; your type already has a perfectly good name,
struct Data. Admittedly you have to type thestructkeyword repeatedly, but that’s not really a problem.Casting the result of
mallocis unnecessary;mallocreturns avoid*result, which can be implicitly converted to your pointer type. The cast can hide errors, such as forgetting the required#include <stdlib.h>.But these are style issues. Your current code:
is ok, and it should work. The problem is later in your code.
scanfwith a"%s"format expects achar* argument. You're giving it the *address* of achar* object, i.e., a value of typechar**. The compiler won’t necessarily warn you about this. So this:should be:
But that’s still a problem, since
tmp->nameis an uninitialized pointer. It probably points to some random location in memory, and the call attempts to store data at that location. Or it could hold an invalid address, causing a crash. The behavior is undefined.You need to allocate space to hold the name, and cause
tmp->nameto point to it. You probably need anothermalloc()call here.So how much space do you need to allocate? Well, there’s no good answer to that, because
scanf("%s", ...)places no limit on how many bytes it will read. However big the allocated space is, you can overflow it if you enter enough data.You probably don’t need to worry about that just yet; just keep it in mind for the future. For now, you can allocate “enough” space (say, 100 bytes) and be careful not to enter too much data. That should be enough to get your program working. (Check the documentation for
scanf, and think about using something like"100s".)And keep in mind that
scanf("%s", ...")reads a whitespace-delimited input string; if you type “John Doe”, it will only read the “John”, leaving ” Doe” for the next input operation.(I hope this isn’t too overwhelming.)