2

Here is a piece of my code, I tried to make it simpler I am trying to assign a string to a pointer inside a struct that is inside an array, also I would like to initialize pointers to NULL so I can check whether or not there is already a doctor using the room... I keep getting seg fault errors I would appreciate any help

struct appointment{
    char *SSN;
    int status;//is appointment already taken?
};

struct room{
    int doctorID;
    char *doctorname;
    struct appointment hours[10];
};

struct room clinic[5];

for(int i = 0; i < 5; i++){    //I was trying to initialize all pointers to NULL but didn't work
    clinic[i].doctorID = 0;
    for(int j = 0; i < 10; i++){
        clinic[i].hours[j].status = 0;
    }
}

for(int i = 0; i < 5; i++){
    clinic[i].doctorname = malloc(sizeof(char) * 30); // Am I doing something wrong here?
    *clinic[i].doctorname = "fernando";
    printf("the name of the doctor on clinic %d is %s\n", i, clinic[i].doctorname
    free(consultorios[i].medico);
    }
return 0;
}
3
  • and also on your malloc... sizeof(char) is 1; so no need. Commented Jun 15, 2013 at 18:21
  • I've found a mistake, it's probably not related but I might as well post it anyway: for(int j = 0; i < 10; i++) has is instead of js. Commented Jun 15, 2013 at 18:27
  • Thanks David, it was my mistake.. you are right... but still I am getting an error when I try to free(clinic[i]doctorname) it says Invalid pointer. Anyways, thanks! Commented Jun 15, 2013 at 18:42

1 Answer 1

3

If you want to assign a string user strcpy instead.

Change your line

*clinic[i].doctorname = "fernando";

to

strcpy(clinic[i].doctorname, "fernando");
Sign up to request clarification or add additional context in comments.

7 Comments

yeah I was just making that comment, your assignment after the malloc will leak the malloc'ed buffer
Is there a way to free the buffer? because I am getting "invalid pointer" when I try to free it using free(). Anyways thank you for the advice!, I will do it the way you say. But I should keep the malloc line and free the memory after that right? sorry, I am a newbie
You should be able to free it using free(), when you are done with its use. Just to point out, your code has free(consultorios[i].medico); which is not freeing .doctorname, that might be issue.
Yes, I am sorry.. my original code is in spanish so I had to translate it to make it more readeble but if I use free(clinic[i].doctorname) is complaining about it being an Invalid pointer and the error is in the function free()
@user2489371, Not sure why that happens with current code. Make sure you are not writing more characters than you allocated.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.