0

I created a simple struct in C language, for storing my data:

typedef struct
{
    int n;
    char *c[];
} simstr;

And, for assignment value to this struct variable, I used this code:

simstr ex =
{
    5,

    "ex_11",
    "ex_12",
    "ex_13",
    "ex_14",
    "ex_15"
};

To test whether ex variable is created correctly, I run this function which I made:

void funct(simstr a)
{
    int i,
        n = a.n;

    for (i = 0; i < n; i++)
    {
        printf("%s\n", a.c[i]);
    }
}

funct(ex);

I compile it successfully. Unfortunately, it returns 2 lines of Θ&; then, this program is stopped because of run-time error.


Could you show me: Why it makes error with the assignment of struct? And how to solve them?

dn174822
  • 21
  • 4

1 Answers1

2

You can't copy structures with a flexible array member like other structures.

The simplest solution is to not involve any copying at all, by using pointers to the structure as function arguments. Then the structure will not be (incompletely) copied.

Use the address-of operator & to create a pointer from the structure.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • And the `->` operator inside the function. – J...S Oct 15 '17 at 12:07
  • I use ANSI standard for C. Is there any suggestion for me? – dn174822 Oct 15 '17 at 12:07
  • @dn174822 Yes. Use pointers. Flexible array members are (as you should know if you followed and read my link) part of the C99 standard, so it's been in "ANSI C" (if by "ANSI C" you mean *standard C*) for soon 20 years. And pointers have always been a natural part of C programming, including the address-of operator. – Some programmer dude Oct 15 '17 at 12:09
  • 1
    @dn174822: AFAIK, there is no flexible array members in ANSI C, so your code is not strict ANSI C compliant to begin with. – rodrigo Oct 15 '17 at 12:10
  • Thank you for your help; unfortunately, I can not up-vote your answer with my account. – dn174822 Oct 15 '17 at 12:11
  • 1
    "You can't copy structures with a flexible array member" - and additionally, you can't portably allocate space for them except by using `malloc` or similar (the initialization of `ex` in the OP is disallowed by the Standard). – aschepler Oct 15 '17 at 13:45