1

I'm working with structures in c, but I can not give value to the structures' attributes.

#include <stdio.h>
#include <string.h>

struct Book{
        char name[10];
        int id;
};

int main(){
        char tmp_name[10];
        int tmp_id;
        for(;;){
                struct Book a;
                scanf("%s",tmp_name);
                scanf("%d", tmp_id);
                strcpy(a.name,tmp_name);
                a.id = tmp_id;
                printf("name: %s\nid:%d", a.name, a.id);
        }

        return 0;
}

This code compiles correctly but occurs Segmentation fault (core dumped) error.

Amir reza Riahi
  • 1,540
  • 2
  • 8
  • 34

4 Answers4

2

You write:

This code compiles correctly ...

In that case I'll strongly recommend that you increase the warning level of your compiler.

For instance "gcc -Wall code.c" may give you a warning like:

In function 'main':
warning: format '%d' expects argument of type 'int *', but argument 2 has type 'int' [-Wformat=]
   15 |                 scanf("%d", tmp_id);
      |                        ~^   ~~~~~~
      |                         |   |
      |                         |   int
      |                         int *

which tell you everything, i.e. you pass an int to a function expecting an int pointer

So just pass an int-pointer like:

scanf("%d", &tmp_id);
            ^
            Take address of tmp_id so that you have a pointer

BTW: for gcc you can use -Werror so that all warnings is treated as errors

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
1

You can directly assign value to struct. You don't need another variable.

struct Book a
scanf("%s", a.name);
scanf("%d", &a.id);
printf("name: %s\nid:%d", a.name, a.id);
John Park
  • 1,644
  • 1
  • 12
  • 17
  • The `scanf("%s", a.name)` offers no protections against a buffer overflow vulnerability, and is no different than the `gets` function, in this respect. `scanf("%9s", a.name)` must have been used instead. – M. Nejat Aydin Aug 11 '20 at 13:32
1

scanf("%d", tmp_id); has to be scanf("%d", &tmp_id);

1

You need to pass in by reference when using scanf.

        scanf("%s", tmp_name);
        scanf("%d", &tmp_id);
eggsu
  • 11
  • 2