简体   繁体   中英

malloc 1D array in struct

I have a struct and I want to malloc() in the struct a 1D array but it doesn't let me. This is my struct.

//n = blabla

struct memory {

    int *results;
    results = malloc(n * sizeof(int));      
    int side;

} *pmemOUT;

The error is "expected specifier-qualifier-list before 'results'" but I don't really get what that means. I read on the internet that this error means that I use something before I declare it but I still can't understand what's wrong.

You cannot allocate memory inside the struct (in fact, you cannot have any statements except member type declarations inside the struct declaration). Either use a constructor (C++), or allocate the memory for the results pointer outside the struct declaration, like

// this statement must be outside the struct definition
pmemOUT->results = malloc(n* sizeof(int));

Example:

#include <stdio.h>
#include <stdlib.h>

int n = 16;
struct memory {
    int *results;
    int side;
} *pmemOUT;

int main()
{
    pmemOUT = (struct memory*)malloc(sizeof(struct memory)); /* allocate memory for the struct */
    pmemOUT->results = (int*)malloc(n * sizeof(int)); /* allocate memory for its member */    
    pmemOUT->results[0] = 10; /* assign something */
    printf("%d\n", pmemOUT->results[0]); /* test that it worked */

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM