-1
#include <stdio.h>

typedef struct StockDetail {
    char* name;
    int code;
    int price;

} Stock;

int main(void)
{
    Stock a[200]; int i; int b;
    for(i=0; i<20 ; i++ )
    {
        printf("Stock %i\n",i+1);
        printf("Name:");
        scanf("%s",a[i].name);
        printf("Code:");
        scanf("%i",&a[i].code);
        printf("Name:");
        scanf("%i",&a[i].price);

    }

    printf("Maximum price of the stock:");
    scanf("%i", &b);

    for(i=0; i<20 ; i++)
    {
        if(a[i].price<=b)
        {
            printf("%s\n",a[i].name);
        }
    }
}

Hi, I'm trying to implement a program that reads 20 stock details such as name, code and price and then ask the user to input a maximum price and print out the stock that cost less than the price. The code looks fine but when I tried to run it gave "segmentation fault" error line.

Nik
  • 1,780
  • 1
  • 14
  • 23
leeebirdy
  • 51
  • 1
  • 1
  • 6

2 Answers2

7

You do not allocate any space for your Stock.name. Use a char[100] or allocate some space.

something like:

for(i=0; i<20 ; i++ )
{
    char tempname[100];
    printf("Stock %i\n",i+1);
    printf("Name:");
    scanf("%s",tempname);
    a[i].name=strdup(tempname);

Don't forget to free it!

Otherwise declare

typedef struct StockDetail {
char name[100];
int code;
int price;

} Stock;
LoztInSpace
  • 5,584
  • 1
  • 15
  • 27
4
scanf("%s",a[i].name);

Here you are taking input in name which is just char* it does not have memory alloted to it, you can declare it as char array with sufficient size or allocate memory with malloc before taking input in it

Pras
  • 4,047
  • 10
  • 20