开发者

I am new to C and I am trying to learn to use structs, my unix app won't run and says EXC_BAD_ACCES. HElP! [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. 开发者_JAVA百科 Closed 11 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜