How do I write a function that generates an instance of a previously defined struct every time it's called? I'm sure since it's an easy problem no context is needed but here is what I have now.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
time_t t;
char names[][40] = {"Name1", "Name2", "Name3"};
struct fighter {
int type;
int strength;
int dexterity;
int resistance;
int weapon;
char name[];
};
struct fighter fighters[];
struct team {
struct fighter f1;
struct fighter f2;
struct fighter f3;
struct fighter f4;
struct fighter f5;
int wins;
int losses;
char name[];
};
struct fighter genf(){
struct fighter genfighter;
memcpy(genfighter.name, names[rand()], 40);
return genfighter;
};
int main(){
srand((unsigned) time(&t));
scanf("%s");
struct fighter f1 = genf();
scanf("%s");
}
And I get this on compilation with gcc.
In function 'genf':
note: the ABI of passing struct with a flexible array member has changed in GCC 4.4.
At top level:
warning: array 'fighters' assumed to have one element.
When running it I get a segmentation fault after one scanf()
You declared a structure with a flexible array data member
nameYou need to allocate dynamically memory for an object of the structure type and its flexible array
nameif you want to store in the array data as you are doing in the functiongenfOtherwise the function invokes undefined behavior.
Also you may not have nested structures with flexible arrays as in this declaration
As for this declaration in the file scope
then it represents a tentative definition equivalent to
Pay attention to that you forgot to specify the second argument that corresponds to the format string
"%s"in this call ofscanfSo it invokes undefined behavior.