简体   繁体   中英

C - Struct- Integer to a pointer without cast

So I'm having a bit of trouble figuring out what is going on when I malloc an array that is a member of the struct ? The following error message occurred :

"assignment makes integer from pointer without a cast".

It would be greatly appreciated if someone can help me see where I went wrong in the malloc .

typedef struct _big_num {
   int  nbytes;  // size of array
   Byte *bytes;  /// array of Bytes
} BigNum;

void initBigNum(BigNum *n, int Nbytes)
{
    int i;
    n->nbytes = Nbytes;
    for (i = 0; i < Nbytes; i++) {
       n->bytes[i] = malloc(sizeof(Byte));   //This is where the error came up
       n->bytes[i] = 0;
       assert(n->bytes[i] == 0);
}
return;
}

n->bytes[i] is of type Byte , it's a single element in the "array". The malloc call returns a pointer .

You don't allocate the array itself, but instead try to allocate each element separately, which isn't how it works. Besides the compiler message, n->bytes may not point to a valid location, making the dereference n->bytes[i] invalid for any index.

You probably want

void initBifNum(BigNum *n, int NBytes)
{
    // Initialize members and allocate memory for array
    n->nbytes = NBytes;
    n->bytes = malloc(sizeof *n->bytes * NBytes);

    // Initialize all elements in the array to zero
    memset(n->bytes, 0, sizeof *n->nbytes * NBytes);
}

n->bytes[i] is really *n->(bytes+i) . So you're assigning the memory address returned by malloc to type Byte instead of to a pointer.

It's worth pointing out that in the very next line, you assign 0 to n->bytes[i] , even though you just attempted to assign it an address. If you're trying to allocate memory that's set to 0, just use calloc - it allocates memory and sets it to 0 for you.

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