1

How can you store a string in a struct array? My code gave me a segmentation fault when I try this. This also happens with the integer.

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
/* get the weight and the object */

struct term{
    char term[200]; // assume terms are not longer than 200
    double number;
};

int main(void)
{   
    struct term *new[12];
    
    char word[13]= "hello world";
    int num =123;
    strcpy(new[0]->term,word);
    new[0]->number = num;


    char word2[20]= "hello new world";
    int num2 =123;
    strcpy(new[1]->term,word2);
    new[0]->number = num2;
}

1 Answers1

2

struct term *new[12] is an array of pointers, they are uninitialized, in order to store anything there you must make your pointers point to some valid memory location, either by allocating memory for them:

struct term *new[12];

for (int i = 0; i < 12; i++)
{
    new[i] = malloc(sizeof **new);
}

Or by othewise assigning them valid struct term variables, i.e.:

struct term st;
new[0] = &st;

Anyway, for such a small array, you could just use a fixed size array, i.e. struct term new[12].

malloc is a heavy function that involves multiple system calls, if you can, you should avoid it.

For better understanding when and where you should use dynamic memory allocation take a look at these:

When and why to use malloc?

When do I need dynamic memory?


There is another problem you should address in your code, char word2[13] = "hello new world" is ill formed, the string is too large for its container. It'll need space for at least 16 chars.

Use empty bounds when assigning strings, i.e. char word2[] = "hello new world", the complier will deduce the needed size for the string, avoiding mistakes like these.


Footnote

new is a reserved keyword in C++, it's used to allocate memory and is the functional equivalent of C's malloc, though it is allowed in C, I would avoid using it to name a variable.

anastaciu
  • 20,013
  • 7
  • 23
  • 43