eepty
eepty

Reputation: 746

Define a pointer with brace in C?

I saw a part of a sample code like this:

1 void func (uint8_t *buffer, uint16_t length)
2 {
3    uint8_t *pack = {0};
4
5    for(int i=0; i<length; i++)
6    {
7       pack[i] = buffer[i];
8    }
9    
10   // send out the "pack" here
11 }

This is a function supposed to fill the data in the "buffer" to "pack", and then send the "pack" out to a serial connection.

What does line 3 do? It is like defining a struct with all elements to 0, but it is a pointer here! Where does this pointer point to? In the following for loop, why it can change to an array (pack[i]) and why we do not need to declare the size like:

uint8_t pack_array[length], *pack;
*pack = pack_array;

The compiler is GCC.

[Edited] : There is a typo in the for loop.

Upvotes: 0

Views: 390

Answers (2)

haccks
haccks

Reputation: 106012

In your snippet, memory is not allocated for pack. Without allocating memory you can't use as subscripted arrays.

for(int i=0; i++; i<length)  

is wrong. i<length should be second expression of for loop.

Upvotes: 0

interjay
interjay

Reputation: 110098

From the C99 standard, 6.7.8p11:

The initializer for a scalar shall be a single expression, optionally enclosed in braces.

The term "scalar" refers to arithmetic types and pointers.

So the braces are allowed, and do nothing.

The line uint8_t *pack = {0}; will initialize the pointer pack with the value 0, so it will be a null pointer.

The following for loop is wrong. Both because the order of expressions in it is incorrect, and because the assignment dereferences pack which is a null pointer.

Upvotes: 3

Related Questions