Copying an array string into a struct

This is a discussion on Copying an array string into a struct within the C Programming forums, part of the General Programming Boards category; Suppose we had: Code: char string[25] = {"hi","ok"}; can we now copy it into a variable in a struct declared ...

  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
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    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
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  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, 08:39 AM
  2. Replies: 8
    Last Post: 04-25-2008, 03:45 PM
  3. Copying a string, into a string array.
    By m.mixon in forum C Programming
    Replies: 5
    Last Post: 07-31-2006, 06:19 PM
  4. Hi, could someone help me with arrays?
    By goodn in forum C Programming
    Replies: 20
    Last Post: 10-18-2001, 10:48 AM

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