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

    Join Date
    Feb 2013
    Posts
    7
    Rep Power
    0

    Unhappy Malloc - warning


    Hi,

    Could you please explane to me what is wrong with my malloc function.

    void AddEntry(phone *phonebook_ptr[])
    {
    phonebook_ptr=(phone*)malloc(sizeof(phone)); //1 - What is wrong here?
    int counter=0;
    counter++;

    printf("Enter first name:\n");
    scanf("%s",phonebook_ptr[counter-1]->Name);

    printf("Enter last name:\n");
    scanf("%s",phonebook_ptr[counter-1]->Suraname);

    printf("Enter phone number:\n");
    scanf("%s",phonebook_ptr[counter-1]->PhoneNumber);
    }

    : warning: assignment from incompatible pointer type [enabled by default]

    2 - Can't add data to Suraname ,why?
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,145
    Rep Power
    2222
    You declared phonebook_ptr thus:
    phone *phonebook_ptr[]
    It is an array of phone pointers, not a single phone pointer.
    phonebook_ptr=(phone*)malloc(sizeof(phone));
    tries to treat phonebook_ptr as a single phone pointer, whereas it is actually an array of pointers. Of course that's not going to work!
    A better way would be
    phonebook_ptr[0] = (phone*)malloc(sizeof(phone));
    but then that would only take care of the first pointer in the array.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    7
    Rep Power
    0
    thanks
  6. #4
  7. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,376
    Rep Power
    1871
    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

IMN logo majestic logo threadwatch logo seochat tools logo