Thread: Copying an array string into a struct

  1. #1
    Cogito Ergo Sum
    Join Date
    Mar 2007
    Location
    Sydney, Australia
    Posts
    463

    Copying an array string into a struct

    Suppose we had:

    Code:
    char string[25] = {"hi","ok"};
    can we now copy it into a variable in a struct declared as:

    Code:
    char alias[25];
    like this:

    Code:
    user->alias = string[2];
    I ask because, I have an array of 104 elements with something similar to that displayed in char string, and I'm trying to copy those elements into a struct variable similiar to char alias, when i do copy it and I print it out, i get strange results, it's like everything was copied but got unorganized and mixed up

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    char string[25] is one string
    Code:
    {"hi","ok"}
    is initializer list for array of 2 strings

    user->alias = string[2]; - no you cannot copy strings like this

    string[2] is one character in your sample
    if string would be defined as array of two strings - index 2 is out of bounds, correct indexes are 0 and 1

    and for copying strings C uses strcpy function
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    Cogito Ergo Sum
    Join Date
    Mar 2007
    Location
    Sydney, Australia
    Posts
    463
    Quote Originally Posted by vart View Post
    char string[25] is one string
    Code:
    {"hi","ok"}
    is initializer list for array of 2 strings

    user->alias = string[2]; - no you cannot copy strings like this

    string[2] is one character in your sample
    if string would be defined as array of two strings - index 2 is out of bounds, correct indexes are 0 and 1

    and for copying strings C uses strcpy function
    Yea it was just an example, the index in the program is correct, but thanks for letting me know, i think what was causing the problem was the incorrect copy of strings.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  2. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  3. Copying a string, into a string array.
    By m.mixon in forum C Programming
    Replies: 5
    Last Post: 07-31-2006, 05:19 PM
  4. Hi, could someone help me with arrays?
    By goodn in forum C Programming
    Replies: 20
    Last Post: 10-18-2001, 09:48 AM