-1

I am trying to initialize an array of structs using a function but when in the middle of the initializing the array of structs, it shows "segmentation fault (core dumped)":

#include <stdio.h>
enum carType
{
    sedan,
    suv,
    hatchback,
    muv
};
typedef enum carType carType;

struct Car
{
    int modelNo;
    char *modelName;
    float price;
    carType type;
};
typedef struct Car Car;

void init(Car* c, int s)
{
    for (int i = 0; i < s; i++)
    {
        scanf("%d", &(c[i].modelNo));
        scanf("%s", c[i].modelName);
        scanf("%f", &(c[i].price));
        scanf("%d", &(c[i].type));
    }
}

int main()
{
    Car arr[2];
    printf("Enter values for members of array of Cars : \n");
    init(arr, 2);

    return 0;
}
Pisers
  • 103
  • 5

1 Answers1

1

You need to allocate space for your character array. Either:

  1. Change the type of modelName from a pointer to an array, also use a format string that ensures you don't write beyond bound and check the return value from scanf():
#define MODEL_NAME_LEN 100 // or whatever suitable size
#define stringify(s) stringify2(s)
#define stringify2(s) #s

// ...

    char modelName[MODEL_NAME_LEN+1];

// ...

        if(scanf("%" stringify(MODEL_NAME_LEN) "s", c[i].modelName) != 1) {
            printf("scanf failed\n");
            return;
        }

  1. Allocating memory in init() with malloc():
#include <stdlib.h>
#define MODEL_NAME_LEN 100 // or whatever suitable size

// ...

void init(Car* c, int s)
{
        // ...

        c[i].modelName = malloc(MODEL_NAME_LEN+1);
        if(!c[i].modelName) {
            printf("malloc failed\n");
            return;
        }

Remember to free() it when done.

  1. If you scanf() implementation supports it you can have it allocate the array for you by using the format string %ms:
        if(scanf("%ms", &c[i].modelName) != 1) {
            printf("scanf failed\n");
            return;
        };

Remember to free() it when done.

If you swap the arguments you can use the syntax init(size_t s, Car c[s]) to document how the two arguments are related. n is usually the default choice of name for a length.

Allan Wind
  • 23,068
  • 5
  • 28
  • 38