Thread: incorrect values in array

  1. #1
    Registered User
    Join Date
    Jan 2014
    Posts
    62

    incorrect values in array

    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?

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    3,744
    This line does NOT copy the value (contents) of a C-String; it just copies the address of a C-String.

    Code:
    msgs[i] = msg;
    Look up strcpy or strncpy functions.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. incorrect print array help
    By stlninja7 in forum C++ Programming
    Replies: 5
    Last Post: 02-27-2012, 09:25 PM
  2. Replies: 8
    Last Post: 01-30-2011, 02:55 PM
  3. first number in array incorrect...
    By sqytoad in forum C Programming
    Replies: 13
    Last Post: 06-09-2008, 11:41 AM
  4. Replies: 1
    Last Post: 05-15-2006, 04:55 PM
  5. Replies: 2
    Last Post: 01-30-2002, 10:09 PM