I am doing some examples out of an older C book [A First Book of ANSI C] and am getting an error while trying to compile this example code:
#include <stdio.h>
struct tele_typ {
char name[30];
char phone_no[15];
struct tele_typ *nextaddr;
};
main() {
struct tele_typ t1 = {"Acme, Sam", "(201) 555-6678"};
struct tele_typ t2 = {"Dolan, Edith", "(213) 682-3104"};
struct tele_typ t3 = {"Lanfrank, John", "(415) 718-4581"};
tele_typ *first; /* create a pointer to a structure */
first = &t1; /* store t1's address in first */
t1.nextaddr = &t2; /* store t2's address in t1.nextaddr */
t2.nextaddr = &t3; /* store t3's address in t2.nextaddr */
t3.nextaddr = NULL; /* store the NULL address in t3.nextaddr */
printf("\n%s %s %s",first->name,t1.nextaddr->name,t2.nextaddr->name);
}
..and the output from gcc newstruct.c -o newstruct
:
newstruct.c: In function 'main':
newstruct.c:13:3: error: unknown type name 'tele_typ'
newstruct.c:15:9: warning: assignment from incompatible pointer type [enabled by default]
newstruct.c:20:28: error: request for member 'name' in something not a structure or union
It's chapter 10.4 on Linked Lists. Is there an error in the book? or has something changed in the standards/gcc version 4.6.2 20120120 (prerelease)
? Thank you!
I couldn't reproduce the first warning; are you sure the code you've pasted here is the code that gives you the warning?
The error unknown type name 'tele_typ'
is easy to fix: you've declared a type struct tele_typ
, but don't have the struct
in front of the line:
tele_typ *first; /* create a pointer to a structure */
If you change this to:
struct tele_typ *first; /* create a pointer to a structure */
It'll compile without error. (And also without warnings in my gcc-4.5.real (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2.)
If you wanted to compile the function body exactly as-is, then you'd also want to add:
typedef struct tele_typ tele_typ;
immediately after the struct tele_typ
definition:
struct tele_typ {
char name[30];
char phone_no[15];
struct tele_typ *nextaddr;
};
typedef struct tele_typ tele_typ;
But I'm a little worried about a C book that doesn't give the main()
function a return type or typed parameters. int main(int argc, char* argv[])
or int main(int argc, char** argv)
is usual, and any book that deviates from these two options strikes me as a little strange. The C Programming Language is a fine book; it is hard to improve upon it for its clarity and correctness. Consider switching to the original.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With