Can one element of a structure access another element in C?

I want to declare int num in struct S. Then the same structure should also have an array B of size num (So Bwill access it numfrom its own structure).

while in function i can do

func(int A)
{
    int max=A; //I could use A directly, I am just trying to explain my plan.
    int B[max];
}

the same won't work for a struct as such,

struct S {
    int num;
    int data[num]; //this is wrong, num is undeclared
};

Can I do this?

+4
source share
4 answers

Use the flexible array element:

struct S {
    int num;
    int data[];
};

int x = 42; 

struct S *p = malloc(sizeof (struct S) + sizeof (int [x]));
p->num = x;
+6
source

There are a few problems with

struct S {
    int num;
    int data[num]; 
};

which make it work not the way you want.

-, num, , num, struct; num (.. num , struct) 1.

, struct union 2. :

struct S {
    int num;
    int data[]; 
};

, ; struct S,

struct S foo;

. :

/**
 * Note that sizeof doesn't try to actually dereference foo below
 */
struct S *foo = malloc( sizeof *foo + N * sizeof *foo->arr );

. : struct S , . 3

, -

struct S {
  size_t num;
  int *data;
};

data struct:

struct S foo;
foo.num = some_value();
foo.data = malloc( sizeof *foo.data * foo.num );

struct S , , :

struct S blah[10];

struct T {
  struct S s;
  ...
};


1. C - ( ), struct/union/enum ( struct, union enum)), struct union ( . ->) . num . ->, .

2. 6.7.2.1/9: " , ".

2. 6.2.7.1/3: (, , ), , ; ( , , , , , ) .
+4

, num , }.

-, ?

, int B[max], (VLA). , . 6.7.2.1/9:

, .

, Ouah.

+3

, , " " , , () , . ( .)

The reason it takes a flexible array in a function is because local function variables are created at the time the function is entered, and then the compiler can take a variable size. (This boils down to the fact that the compiler allocates more memory on the stack and compensates for all calls to local variables with size, but different compilers may have a different approach.)

#include <stdio.h>
int size;
struct S {
    int num;
    int a[size];    // illegal: size must be known at compile time
};

int f(int size)
{
    int a[size];   // legal as a is allocated on the stack
    ....
}

The following will be legal:

#include <stdio.h>
#define A_SIZE 10
struct S {
    int num;
    int a[A_SIZE];    // legal: A_SIZE is known at compile time
};

Ps: I am not a C99 programmer; I may have some errors.

+2
source

Source: https://habr.com/ru/post/1605959/


All Articles