-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.

1
  • Next time try to produce a minimal reproducible example! there are more lines that are not executed than there are lines that actually are. Commented Nov 14, 2017 at 7:19

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.