#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    7
    Rep Power
    0

    Red face Transfer data to a pointer of a struct.


    Hi
    could you please help,
    I get this error while trying to transfer data to a pointer of a struct.

    Error:
    incompatible types when assigning to type ‘char[20]’ from type ‘char


    the struct:

    Code:
    typedef struct PhoneBook
    {
    	char Name[20];
    	char Suraname[20];
    	char PhoneNumber[20];
    }phone;
    the code:
    Code:
    void AddEntry(phone *phonebook_ptr)
    {
    
    	char A[20];
    	printf("Enter name:\n");
    	scanf("%s",A);
    	phonebook_ptr->Name=A;
    
    
    }
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,403
    Rep Power
    1871
    You need to use strcpy()
    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
  4. #3
  5. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,216
    Rep Power
    2222
    More specifically, you are not copying the string A into your struct with that assignment statement, but rather you are attempting a damned illegal thing: assigning a pointer value to an array name. That is why you got that error message.

    Now, if you had declared Name to be a char pointer, you would not have gotten that error message, but you would still have made an enormous mistake. Because in that case, you would have assigned a char pointer, the address of A, to that char pointer in that struct and when A goes away when you leave that function then your struct will be pointing to garbage. And even if you made A a global or a static, then every time you called that function to enter a different name into a different struct, all structs' Name fields would immediately change to the new name input.

    Instead, you need to copy the contents of A into Name. You need to use strcpy().

IMN logo majestic logo threadwatch logo seochat tools logo