Here's the code:
#include <stdio.h>
int main (int argc, const char * argv[]) { int num; struct contact;
struct contact {
double foneNumber;
char firstName;
char lastName;
};
typedef struct contact cntct;
cntct bob;
bob.foneNumber = 15555555555;
bob.firstName = "bob";
bob.lastName = "builder";
cntct fudge;
fudge.foneNumber = 15444444444;
fudge.firstName = "fudge";
fudge.lastName = "cornelius";
cntct Siddhartha;
Siddhartha.foneNumber = 15333333333;
Siddhartha.firstName = "Siddhartha";
Siddhartha.lastName = "Gautama";
while (1) {
printf("Would you like to see contact 1, 2, or 3 (0 to quit)?");
scanf("%d", &num);
switch (num)
{
case 1:
printf("Phone Number: %lg", bob.foneNumber);
printf("\nFirst Name: %s", bob.firstName);
printf("\nLast Name: %s", bob.lastName);
break;
case 2:
printf("Phone Number: %lg", fudge.foneNumber);
printf("\nFirst Name: %s", fudge.firstName);
printf("\nLast Name: %s", fudge.lastName);
break;
case 3:
printf("Phone Number: %lg", Siddhartha.foneNumber);
printf("\nFirst Name: %s", Siddhartha.firstName);
printf("\nLast Name: %s", Siddhartha.lastName);
break;
case 0:
return 0;
break;
default:
printf("huh?");
return 0;
}
}
}
In your struct you should use char pointers to hold the address of strings, not chars:
struct contact {
double foneNumber;
char * firstName;
char * lastName;
};
Otherwise, when you call printf
with %s
, it expects the parameter to be an address
to char, but instead it gets some value (which is the value of the char) and this is in most cases an invalid address.
精彩评论