have an assignment where I should use the following struct:
typedef struct natset{
unsigned long min;
unsigned int size;
unsigned char* bits;
}natset_t;
Now I have to assign that pointer to the following two-dimensional array of unsigned chars:
unsigned char bArrayRoll[7][byteNum];
Which I have tried doing like so:
unsigned long min = 20;
unsigned int size = 20;
unsigned char bArrayRoll[7][byteNum];
natset_t newNatset;
newNatset.min = min;
newNatset.size = size;
newNatset.bits = &bArrayRoll;
Variations of that newNatset.bits which I have tried include:
newNatset.bits = bArrayRoll;
newNatset.bits* = &bArrayRoll;
However, the compiler either returns "Assignment from incompatible pointer type" or "Initialization from incompatible pointer type".
How can I assign the bits pointer to this array correctly?
newNatset.bits* = &bArrayRoll;
You are trying to multiply newNatset.bits
with the address of bArrayRoll
, this is undefined behavior.
newNatset.bits = bArrayRoll;
This one here is trying to assign unsigned char (*)[byteNum]
to unsigned char*
which is again something about which compiler complained. Types are incompatible clearly.
Correct one would be (correct one as per the compiler)
newNatset.bits = bArrayRoll[0];
This is once again a type incompatible assignment. You are assigning unsigned char
to unsigned char*
. You can do this though,
newNatset.bits = &bArrayRoll[0][0];
Then you need to do this,
unsigned char (*p)[byteNum] = bArrayRoll;
but in the structure you have declared bits
to be of type unsigned char*
not of type unsigned char (*)[byteNum]
.
Well if you didn't understand what happened when we assigned in the last case and how did the types match - then here is the key idea.
The 2d array decays into the pointer to the first element - which is a single dimensional array of byteNum
unsigned characters. Now we are assigning it to p
which is again
unsigned char (*)[byteNum]
^ ^
1 2
\-----------/
3
Pointer to (1) an array of bytenum (2) unsigned characters (3).
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.