I have this simple program below:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
unsigned long long int address;
float current;
unsigned char pressure_units;
} sensor;
sensor createSensor(unsigned long long int address, float current, unsigned char pressure_units)
{
sensor temp;
temp.address = address;
temp.current = current;
temp.pressure_units = pressure_units;
return temp;
}
int main(int argc, char *argv[])
{
int i;
sensor sensors[3];
char msg[100];
char *msgs[3];
char wholeMsg[300];
for(i=0;i<3;i++)
{
sensors[i] = createSensor(10000*i,i+3.0,i);
}
for(i=0;i<3;i++)
{
int n = sprintf(msg,"address:%llu,current:%f,pressure_units:%u", sensors[i].address, sensors[i].current, sensors[i].pressure_units);
if(n <= 100)
{
msgs[i] = msg;
}
}
sprintf(wholeMsg,"%s\n%s\n%s\n",msgs[0],msgs[1],msgs[2]);
printf("whole message: %s",wholeMsg);
}
The problem is it prints this:
whole message: address:20000,current:5.000000,pressure_units:2
address:20000,current:5.000000,pressure_units:2
address:20000,current:5.000000,pressure_units:2
rather than this:
whole message: address:0,current:3.000000,pressure_units:0
address:10000,current:4.000000,pressure_units:1
address:20000,current:5.000000,pressure_units:2
As you can see, it has stored the last struct in all three indexes of the array. Why?