Thread: change struct

  1. #1
    Registered User
    Join Date
    May 2007
    Posts
    4

    change struct

    hello everyone,
    There is an error with the struct, the message of error is this:
    error:incompatible types in assignment
    Code:
    Code:
    #include <stdio.h>
    
    struct RegisterUser{
    char name[10];
    int age;
    }user;
    
    
    int main(){
    user.name = "Someone"; //There is the error
    }
    What i should change in my code?

    Thanks

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Code:
    strcpy(user.name,"Someone");
    Problem: If you try to copy a string larger than user.name can hold, you can cause a security flaw in your program and cause hard to find bugs. Consider using something like:

    Code:
    strncpy(user.name,"Someone",sizeof(user.name));

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    But beware that strncpy by itself doesn't guarantee a \0 at the end, thus potentially causing other problems.

    Code:
    #include <stdio.h>
    #include <string.h>
    
    void safer_strncpy ( char *dst, const char *src, size_t len ) {
        strncpy( dst, src, len );
        if ( dst[len-1] != '\0' ) {
          fprintf(stderr,"&#37;s truncated at %lu characters\n", src, (unsigned long)len-1 );
        }
        dst[len-1] = '\0';
    }
    
    int main ( ) {
        char dst[5];
        safer_strncpy( dst, "this", sizeof(dst) );
        printf("%s\n",dst);
        safer_strncpy( dst, "world", sizeof(dst) );
        printf("%s\n",dst);
        return 0;
    }
    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. Concatenating in linked list
    By drater in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 11:10 PM
  2. Replies: 10
    Last Post: 05-18-2006, 11:23 PM
  3. Binary Search Tree
    By penance in forum C Programming
    Replies: 4
    Last Post: 08-05-2005, 05:35 PM
  4. towers of hanoi problem
    By aik_21 in forum C Programming
    Replies: 1
    Last Post: 10-02-2004, 01:34 PM
  5. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 03:58 PM