2

Need help with array assignment

In my code i am declaring array as shown below.

u8 sendbuffer_1[4];

In my main, i am assigning it as shown below.

sendbuffer_1[] = {":K1\r"};

I tried removing the square brackets as well but doesn't work!!

Get error (with the square brackets)

../src/helloworld.c: In function 'main':
../src/helloworld.c:80:18: error: expected expression before ']' token
sendbuffer_1[] = {":K1\r"};

Error(Without square bracket)

../src/helloworld.c: In function 'main':
../src/helloworld.c:80:20: error: expected expression before '{' token
 sendbuffer_1 = {":K1\r"};

Please let me know the issue. Thanks in advance!!

1
  • One too short: you didn't allow for the nul terminator. u8 sendbuffer_1[5] = ":K1\r"; or just u8 sendbuffer_1[] = ":K1\r"; Commented Apr 9, 2016 at 19:57

2 Answers 2

1

You can't assign arrays in C. You can initialize them, but you can't assign them.

This is an initialization:

u8 sendbuffer_1[4] = {":K1\r"};

It wouldn't be legal in C++; it is in C but the sendbuffer_1 array is not null terminated. That's dangerous if you're expecting a string.

Otherwise, you'd use memmove() or something similar to set the array:

memmove(sendbuffer_1, ":K1\r", sizeof(sendbuffer_1));

Beware of the sizes of the source string (":K1\r") and the destination string; the length copied should be the minimum of the two sizes. That is, if sendbuffer_1 was an 80-character buffer, the memmove() would not be safe, not because sendbuffer_1 would be overflowed, but because you'd be accessing beyond the end of the string). Be very careful in C.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot!!That
"Be very careful in C" +1.
0

Either when initializing your array:

u8 sendbuffer_1[] = {":K1\r"};

Or if you need to assign these values in your main function you'll need to insert each value individually as follows:

sendbuffer_1[0] = ':';
sendbuffer_1[1] = 'K';    
sendbuffer_1[2] = '1';
sendBuffer_1[3] = '\r';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.