Thread: Struct and string ?

  1. #1
    Registered User
    Join Date
    Sep 2004
    Posts
    7

    Struct and string ?

    x.name = fname, dont work, why ?
    and how can I solve it ?

    #include<stdio.h>

    struct example
    {
    char name[10];
    int year;
    };

    int main(void)
    {
    struct example x;
    char fname[10] = "John";
    int number = 1930;


    x.name = fname;
    x.year = number;

    return 0;
    }

    oldman 1940

  2. #2
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,820
    Woop?

  3. #3
    Registered User caroundw5h's Avatar
    Join Date
    Oct 2003
    Posts
    751
    simple answer: your copying the adress and not the string itself. For that you use the strcpy function found in string.h
    Code:
    #include<stdio.h>
    #include <string.h>
    
    struct example
    {
    char name[10];
    int year;
    };
    
    int main(void)
    {
    struct example x;
    char fname[10] = "John";
    int number = 1930;
    
    
    strcpy(x.name, fname);
    x.year = number;
    
    puts(x.name);
    printf("%d", x.year);
    
    //getchar();
    
    return 0;
    }
    You might want to take a look at the following links. If you are on structures already you should be familar with the string capabilities of C and its nuances.
    some links
    Last edited by caroundw5h; 01-08-2005 at 02:40 PM.
    Warning: Opinions subject to change without notice

    The C Library Reference Guide
    Understand the fundamentals
    Then have some more fun

  4. #4
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    I know you'd probably already know the solution by now lol, but just in case, Change This:
    Code:
    x.name = fname;
    To This:
    Code:
    strcpy(x.name, fname);
    Why? Because changing the value of an array in C has to be done item by item. In this case, the items would be in the form of a lot of char variables. I hope that makes things a little clearer.

    ---Edit---
    caroundw5h just highlighted his code before I posted :(, and I didn't think of #including <string.h>, hmmmm :)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. memory issue
    By t014y in forum C Programming
    Replies: 2
    Last Post: 02-21-2009, 12:37 AM
  2. Link List math
    By t014y in forum C Programming
    Replies: 17
    Last Post: 02-20-2009, 06:55 PM
  3. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  4. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM