Daniela Maia Daniela Maia - 4 months ago 23
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++){
strucSend.vec[i]=i+1;
strucSend.vec[i]=100;
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
int
to a
float
?

Answer
  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.


EDIT:

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

strucSend.vec[i]=i+1;
strucSend.vec[i]=100;

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

Comments