Data structure problem

I created a structure like this:

struct ponto {
    int x;
    int y;
    int z;
};

1) Is it possible to initialize an int with a default value? int var = value; doesn't seem to work, the compiler says "syntax error before" = "token" or something like that.

2) I need to work with several of them, as in an array of structures, but I only know how much I need after starting the application after reading the file. How to do it?

Thanks in advance

EDITOR: So many answers, I am grateful. Unfortunately, I can only note one

+3
source share
7 answers

a) You can activate with

struct pronto p = {1,2,3};

In recent compilers (not sure how portable this is, think C99?)

b) malloc:

struct pronto *array = malloc(sizeof(struct pronto) * NUMBER);
+2

0, :

struct ponto foo = { 0 };

malloc() :

struct ponto *arr = (struct ponto *) malloc(COUNT * sizeof(struct ponto));

free() , .

+1
struct ponto* create_and_init_ponto(int n)
{
    struct ponto* array;
    int i;

    array = (struct ponto*)malloc( n * sizeof(struct ponto) );

    for ( i = 0; i < n; ++i )
    {
        array[ i ].x = 0;
        array[ i ].y = 0;
        array[ i ].z = 0;
    }

    return array;
}
+1

, , :

struct ponto xyz;
xyz.x = 7;

:

int need_to_have = 24;
struct ponto *pontos = malloc (need_to_have * sizeof(struct ponto));
0
0

1) , C , ( / ). , all-zeros , :

struct foo myfoo = {0};

{0} , .

, - , , , :

#define FOO_INITIALIZER { 1, 2, 3 }
struct foo myfoo = FOO_INITIALIZER;

2) , - , , malloc , :

if (count > SIZE_MAX / sizeof *bar) abort();
struct foo *bar = malloc(count * sizeof *bar);

malloc .

, , , , , , , . . realloc.

0

№1: int :

struct ponto p1;
p1.x = p1.y = p1.z = 3;  // initializing with three

, 0, memset :

memset(&p1, 0, sizeof(struct ponto));

№ 2: malloc:

struct ponto *ps;
ps = (struct ponto *)malloc(N*sizeof(struct ponto));
// where N is your element count.

N struct ponto. :

int initvalue = 3; // assuming you want to initialize points with value 3
for (i=0; i<N; i++) {
    ps[i].x = ps[i].y = ps[i].z = initvalue;
}
-3

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


All Articles