Daniela Maia Daniela Maia - 5 months ago 35
C Question

can't write to a vector in a struct c

I'm trying to write to a vector in a struct, but it is not working.
Here's my code:

#define BUFFER_SIZE 100

typedef struct {
float vec[BUFFER_SIZE];
int j;
} send;

int main(){

send strucSend;

for(i=0; i<BUFFER_SIZE; i++){
printf("created vec: %d \n", strucSend.vec[i]);

When I print it, it's all zeroes. Compiled using

gcc -o main main.c -lpthread -lrt

no errors or warnings compilling.
What am I doing wrong? Thanks in advance for helping.

EDIT: is it because I'm trying to assign and
to a

  1. i is not defined.

  2. You're using an int value for float. Are you sure?

  3. In your code strucSend.vecsaldos[i] has no meaning. You don't have a a member called vecsaldos. If you meant strucSend.vec[i], then that is of type float. You've to use %f conversion specifier for that.


Simply change the %d to %f, as you're printing float. Otherwise, using improper conversion specifier causes undefined behaviour.

Related: From C11, chapter ยง7.21.6.1, fprintf()

If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

So, to answer,

When I print it, it's all zeroes

Ans: Result of UB.

Also, as Mr. @Gopi Mentioned, there is a logical mistake in


here, the first statement is effectively useless, as you're overwriting the same value. Maybe you want to modify that part, too.