amedeiros
amedeiros

Reputation: 949

C Structures Bus Error 10

I have a stuct in C, and I use a function to get the values for the structure from the user. Below is my structure.

typedef struct {
    char    *name;
    char    *chemical_symbol;
    char    *class;
    int     atomic_number;
    double  atomic_weight;
    int     *electrons;
} element_t;

This is the function I am using to get the values from the user. The problem lies in this function after asking for the chemical symbol. I get Bus Error: 10. My understanding of a bus error is when the processor cant attempt the memory access. Any help is appreciated. Thank you!

element_t scan_element() {

    element_t element;

    printf ("Enter New Element Information:\n\n");

    printf("Element Name: ");
    scanf("%s", element.name);

    printf("Element Chemical Symbol: ");
    scanf("%s", element.chemical_symbol);

    printf("Element Class: ");
    scanf("%s", element.class);

    printf("Element Atomic Number: ");
    scanf("%d", &element.atomic_number);

    printf("Element Atomic Weight: ");
    scanf("%lf", &element.atmoic_weight);

    printf("Element Electrons: ");
    scanf("%p", &element.electrons);

    return(element);
}

Upvotes: 0

Views: 1102

Answers (4)

paulsm4
paulsm4

Reputation: 121799

You need to allocate memory. Perhaps the best (certainly easiest!) way is simply define your struct to have character arrays (instead of character pointers).

EXAMPLE:

#define MAX_STRING 80
#define MAX_ELECTRONS 32

typedef struct {
    char    name[MAX_STRING];
    char    chemical_symbol[MAX_STRING];
    char    class[MAX_STRING];
    int     atomic_number;
    double  atmoic_weight;
    int     electrons[MAX_ELECTRONS];
} element_t;

Upvotes: 2

Rontogiannis Aristofanis
Rontogiannis Aristofanis

Reputation: 9063

Before you scan the strings, you should allocate some space for them. For example:

void initialize( element_t * p ) {
  p->name = malloc( sizeof( char ) * MAXSIZE );
  p->chemical_symbol = malloc( sizeof( char ) * MAXSIZE );
  p->class = malloc( sizeof( char ) * MAXSIZE );
}

Before you call scan_element, call initialize. I' m sure it will compile properly.

Upvotes: 0

md5
md5

Reputation: 23717

You didn't allocate enough memory to attempt to read into your strings.

BTW, your last scanf is strange: do you really want to ask an address? It could be dangerous.

Upvotes: 2

ouah
ouah

Reputation: 145899

printf("Element Name: ");
scanf("%s", element.name);

You have to allocate memory for the object pointed by element.name for example by using malloc. Without proper allocation element.name is an invalid pointer.

Upvotes: 4

Related Questions