Thread: Array of Structs, setting value of struct

  1. #1
    Registered User
    Join Date
    Sep 2009
    Posts
    11

    Array of Structs, setting value of struct

    hey i was wondering if there's any way that can set they value of an
    array of structs the way I tried to do below for ray[1]. That code on that
    line kills everything but I didn't want to have to create a demo object then assign
    it as i did for ray[0]. Anyway around this? or do i have 2 always create an object first?

    Thanx



    Code:
    #include<iostream>
    using namespace std;
    
    struct demo {
    
    	int val;
    	int vol;
    	int vel;
    
    };
    
    int main() {
    
    	
    	demo dem = {1,2,3};
    		
    	demo ray[5];
    
                   ray[0] = dem;  //This works
    
    	ray[1] = demo{3,2,1};   //This kills the program
    	
    }

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    You need to use two steps.
    Code:
    demo temp = {3,2,1};
    ray[1] = temp;
    Rather than "kills the program" (a meaningless description) it would have been better to say "does not compile". There is an art to getting useful responses, and a key part of it is asking clear questions.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Lemme get this right, you posted C++ code on the C forum because?

    Because if it really is C++ code, then you can give your struct some constructors, and be home and dry.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help with linked list sorting function
    By Jaggid1x in forum C Programming
    Replies: 6
    Last Post: 06-02-2009, 02:14 AM
  2. null struct to terminate array of structs?
    By eccles in forum C Programming
    Replies: 6
    Last Post: 01-24-2005, 06:27 AM
  3. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  4. accessing array of structs values
    By WaterNut in forum C++ Programming
    Replies: 12
    Last Post: 07-08-2004, 08:47 PM
  5. Passing pointers between functions
    By heygirls_uk in forum C Programming
    Replies: 5
    Last Post: 01-09-2004, 06:58 PM