Little question about structures...

This is a discussion on Little question about structures... within the C Programming forums, part of the General Programming Boards category; Hello, sorry if this seems like a trivial query but I was having some issue setting a string to a ...

  1. #1
    Registered User
    Join Date
    Dec 2009
    Posts
    12

    Little question about structures...

    Hello,

    sorry if this seems like a trivial query but I was having some issue setting a string to a char array in a structure. I have a set up like this:


    Code:
    Code:
    struct Computer  
    {  
    char Manufacturer[30];  
    float Price;  
    int Memory;  
    } *PC;

    i need to set the Manufacturer to HAL,using only the arrow operator. how can i do that?

  2. #2
    Epy
    Epy is offline
    Fortran lover Epy's Avatar
    Join Date
    Sep 2009
    Location
    California, USA
    Posts
    965
    Last edited by Epy; 12-17-2009 at 06:32 AM. Reason: added link for reference

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You can't assign arrays with the assignment operator.


    Quzah.
    Hope is the first step on the road to disappointment.

  4. #4
    Registered User jeffcobb's Avatar
    Join Date
    Dec 2009
    Location
    Henderson, NV
    Posts
    875
    strncpy(PC->Manufacturer, "HAL", 4);
    C/C++ Environment: GNU CC/Emacs
    Make system: CMake
    Debuggers: Valgrind/GDB

  5. #5
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,246
    Quote Originally Posted by jeffcobb View Post
    strncpy(PC->Manufacturer, "HAL", 4);
    There's no point in passing the size of the source buffer to strncpy. To avoid buffer overruns, it should actually look more like:

    Code:
    strncpy(PC->Manufacturer, "HAL", sizeof(PC->Manufacturer));
    PC->Manufacturer[sizeof(PC->Manufacturer)-1] = '\0'; // since strncpy() isn't guaranteed to null terminate
    Of course if you know that the string will fit, you can just use strcpy() instead.
    bit∙hub [bit-huhb] n. A source and destination for information.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Design layer question
    By mdoland in forum C# Programming
    Replies: 0
    Last Post: 10-19-2007, 04:22 AM
  2. Exam Question - Possible Mistake?
    By Richie T in forum C++ Programming
    Replies: 15
    Last Post: 05-08-2006, 03:44 PM
  3. Replies: 4
    Last Post: 02-02-2003, 04:45 AM
  4. Question about structures
    By Randoon in forum C Programming
    Replies: 2
    Last Post: 12-12-2002, 10:47 PM
  5. Very simple question, problem in my Code.
    By Vber in forum C Programming
    Replies: 7
    Last Post: 11-16-2002, 02:57 PM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21