Can't assign string to pointer inside struct - c

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;
}

If you want to assign a string user strcpy instead.
Change your line
*clinic[i].doctorname = "fernando";
to
strcpy(clinic[i].doctorname, "fernando");

Related

How to use table pointer with fonction in C [duplicate]

This question already has answers here:
Passing 2D array of const size
(5 answers)
Closed 2 months ago.
This post was edited and submitted for review 2 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I have a struct like:
struct oda {
char isim[10];
int id[1];
};
and 2d table created with this type:
struct oda* tab[X][Y];
This table should be allocated dynamically on memory, so if we have product placement on x and y tab[X][Y] should point to our struct, otherway value of pointer tab[X][Y] = NULL
I have created a fonction for init this table:
void init_tab_empty(struct oda** ptr_tab)
{
int i, j;
for (i = 0; i < X; i++) {
for (j = 0; j < Y; j++) {
ptr_tablo[i][j] = NULL;
}
}
}
But this is not working, i have:
Cannot assign a value of type void * to an entity of type struct oda
Can you help me please?
I played with *'s but i can't understand what can i do more
it seems correct for me but not working
If I understood you well, you want to pass a table to your function. Then the following change will make it okay:
void init_tab_empty(struct oda ***tab)
{
int i, j;
for (i = 0; i < DIM_X; i++) {
for (j = 0; j < DIM_Y; j++) {
tab[i][j] = NULL;
}
}
}
This tells the function that you will input a table of pointers to struct oda data type.
There, you have:
struct oda *my_tab[DIM_X][DIM_Y];
...
init_tab_empty(my_tab);

Adding element to array, old values turns to 0 but new shows

I have written this program where I can add pics to a staff using their names. but right now it adds the new value but the already existing values becomes 0.
this is the outcome:
type in the name you would like to add pic to
Anna
type in pic
55
1.Show existing
2.add pic to a staff
1
Adam 1,2,3,
Anna 0,0,0,55,
the rest of the code:
typedef struct Staff
{
char name[30];
int *pic;
int imagecount;
} Staff;
void printStaff(Staff *pStaff)
{
printf("%s ", pStaff->name);
if ( pStaff->pic) {
for(int i=0; i<pStaff->imagecount; i++){
printf("%d,",pStaff->pic[i]);
}
}
printf("\n");
}
void PrintList(Staff aLista[], int staffCount)
{
for (int i = 0; i < staffCount; i++) {
printStaff(&aLista[i]);
}
}
UPDATED CODE:
Staff addpic(Staff array[], int staffCount)
{
Staff newStaff = {};
printf("type in the name you would like to add pic to \n");
fgets(newStaff.name, 30, stdin);
for(int i = 0; i< staffCount; i++) {
if(strcmp(array[i].name,newStaff.name)==0) {
if(array[i].imagecount<5) {
printf("type in pic\n");
int newpic;
scanf("%d",&newpic);
array[i].imagecount++;
int *newpics = realloc(newStaff.pic, (array[i].imagecount) * sizeof(int));
newpics[array[i].imagecount-1] = newpic;
array[i].pic = newpics;
}
}
}
return newStaff;
the rest of the code:
int main(void)
{
int staffCount=0;
int input;
int test[3] = {1,2,3};
Staff myStaff[5] = { {"Adam", test, 3},{"Anna",test,3} };
staffCount=2;
do
{
printf("1.Show existing \n");
printf("2.add pic to a staff");
printf("\n");
scanf("%d", &input);
switch(input)
{
case 1:
PrintList(myStaff,staffCount);
break;
case 2:
addpic(myStaff,staffCount);
break;
default:
printf("inccorect inpput\n");
break;
}
}while (input<'1' ||input<'2');
return 0;
}
any help is appreciated, but I'm new to coding so keep that in mind.
In the addpic function you do
int *newpics = realloc(array[i].pic, ...);
One problem is that if you do it for one of the two elements you have initialized in array, then array[i].pic is pointing to the first element of an array (the array test in the main function).
Arrays can not be reallocated. If you want to reallocate the memory you need to allocate the original memory dynamically as well.
newStaff.pic is initialized to NULL and not updated then, so realloc(newStaff.pic, (array[i].imagecount) * sizeof(int)); is equivalent to malloc((array[i].imagecount) * sizeof(int));.
Elements allocated via malloc() and not initialized hae indeterminate value, and they happened to be zero in this case.
You can take over the contents by manually copying them.
int *newpics = realloc(newStaff.pic, (array[i].imagecount) * sizeof(int));
/* add this line to copy contents */
for (int j = 0; j < array[i].imagecount-1; j++) newpics[j] = array[i].img[j];
newpics[array[i].imagecount-1] = newpic;
Unfortunately, this method is not good because this may cause memory leak if addition like this to the same element of array is done multiple times.
Better way is to allocate the buffer to assign to img dynamically and pass them to realloc(). Then, realloc() will do the copying for you.
Initialization part:
int test[3] = {1,2,3};
Staff myStaff[5] = { {"Adam", test, 3},{"Anna",test,3} };
staffCount=2;
/* add this to change statically allocated arrays to dynamically allocated ones */
for (int i = 0; i < staffCOunt; i++) {
int* newpics = malloc(myStaff[i].imagecount * sizeof(int));
for (int j = 0; j < myStaff[i].imagecount; j++) newpics[j] = myStaff[i].img[j];
myStaff[i].img = newpics;
}
Updating part:
/* use array[i].pic instead of newStaff.pic */
int *newpics = realloc(array[i].pic, (array[i].imagecount) * sizeof(int));
/* then, no manual copying is required */
(error checkings are omitted)

Having trouble making memset function?

void memSet(char destination[], char valueMemSet, int numOfValue)
{
char temp;
int j=1;
for (int i = 0; i <= numOfValue; i++)
{
temp = destination[i];
destination[i] = valueMemSet;
destination[j] = temp;
j++;
}
}
The array is originally "this is the source Concatenate means to link."
This is what I am trying to get "------this is the source Concatenate means to link."
This is What I am currently getting "-------Tthe source Concatenate means to link."
When I ran the debugger it saves the first letter of the array but every single one after gets replaced.
How can I solve this issue?
memset() is a function, which sets a particular value in a given memory, like you want to initialize total array's elements to some particular value(for eg - zero). So it will set the same in that array.
what you need here is strcat() function.
Is that what you need?
void memSet(char destination[], char valueMemSet, int numOfValue, int len)
{
int j=len-numOfValue;
for (int i = len-1;i>=numOfValue;i--) {
destinstion[i] = destination[j--];
}
for (int i = 0; i < numOfValue; i++)
{
destination[i] = valueMemSet;
}
}

Initializing Strings in an Array of Sturts within a Struct

I have a struct gradebook with(among other things) an array of student structs that has two string fields
#define MAX_NAME_LEN 50
#define MAX_EMAIL_LEN 80
#define MAX_NUMBER_OF_STUDENTS 200
#define MAX_NUMBER_OF_ASSIGNMENTS 100
typedef struct students {
char *name;
char *email;
} Students;
typedef struct gradebook {
int number_of_students;
Students students[MAX_NUMBER_OF_STUDENTS];
int number_of_assignments;
char assignments[MAX_NUMBER_OF_ASSIGNMENTS][(MAX_NAME_LEN + 1)];
int scores[MAX_NUMBER_OF_STUDENTS][MAX_NUMBER_OF_ASSIGNMENTS];
} Gradebook;
I have an initialization function
int init_gradebook(Gradebook *book) {
int row, col, ndx, count;
book->number_of_students = 0;
count += book->number_of_students;
for(ndx = 0; ndx < MAX_NUMBER_OF_STUDENTS; ndx++) {
book->students[ndx].name = 0;
book->students[ndx].email = 0;
}
book->number_of_assignments = 0;
count += book->number_of_assignments;
for(row = 0; row < MAX_NUMBER_OF_ASSIGNMENTS; row++) {
for(col = 0; col < (MAX_NAME_LEN + 1); col++) {
book->assignments[row][col] = 0;
count += book->assignments[row][col];
}
}
for(row = 0; row < MAX_NUMBER_OF_STUDENTS; row++) {
for(col = 0; col < MAX_NUMBER_OF_ASSIGNMENTS; col++) {
book->scores[row][col] = 0;
count += book->scores[row][col];
}
}
if (count == 0) {
return 1;
} else {
return 0;
}
}
and I need to then insert, into those two string fields, the passed in strings, with my add_student function.
int add_student(Gradebook *book, char *nom, char *mail) {
int ndx, count;
if (book->number_of_students == 0) {
book->students[(book->number_of_students)].name = malloc(sizeof(51));
book->students[(book->number_of_students)].email = malloc(sizeof(81));
strcpy(book->students[(book->number_of_students)].name, nom);
strcpy(book->students[(book->number_of_students)].email, mail);
book->number_of_students++;
} else {
for (ndx = 0; ndx < book->number_of_students; ndx++) {
book->students[(book->number_of_students)].name = malloc(sizeof(51));
book->students[(book->number_of_students)].email = malloc(sizeof(81));
strcpy(book->students[(book->number_of_students)].name, nom);
strcpy(book->students[(book->number_of_students)].email, mail);
book->number_of_students++;
}
}
return 1;
}
My code compiles, but when I run it with the main function, I get a seg fault. The add_student function is what I am ultimately trying to do (copy the given string into book->student[ndx].name) If you need to see the main file or the gradebook.h file, let me know.
Edit: Thanks to all of you, this issue has been solved. The main problem, as abginfo pointed out, was my If Else + the For loop inside of it. But now I have other problems further along in my program. Haha, Thank You.
From what portion of your code I can see, I'm going to make the assumption that the init_gradebook function takes a non allocated reference to gradebook and attempts to initialize it.
In this case the gradebook reference you have has no memory allocated to it just yet. Try using the malloc() function to assign the required memory to your gradebook reference before attempting to initialize the rest of its variables.
gb = (Gradebook*)malloc(sizeof(*Gradebook));
I've changed the variable name to avoid any confusion.
To supplement varevarao's answer, you should allocate everything explicitly as a matter of habit instead of relying on segfaults to tell you something's not allocated. (Not that you necessarily do!) Messing with unallocated memory is undefined behavior, so in some cases this code does not trigger an error -
int main (void) {
Gradebook mybook;
init_gradebook(&mybook);
printf("there are %i students\n", mybook.number_of_students);
add_student(&mybook, "blerf", "blerf#gmail.com");
printf("now there are %i students\n", mybook.number_of_students);
printf("%s has an email address of %s\n", mybook.students[0].name, mybook.students[0].email);
return 0;
}
returned (on my machine)
there are 0 students
now there are 1 students
blerf has an email address of blerf#gmail.com

struct member is not found

I have the following struct:
typedef struct vertex_tag{
int visited = 0;
int weight = FLT_MAX;
int prev;
}vertex_t;
It has the three members as indicated above.
I malloc the vertex like this:
vertex_t * vertex[G->vertices];
for(i=0; i < G->vertices; i++)
{
vertex[i] = (vertex_t*)malloc(sizeof(vertex_t));
}
So I create a matrix from the struct. I then call them throughout the function I created like this:
vertex[i]->visited
vertex[i]->weight
vertex[i]->prev
I keep getting the following error:
error: ‘vertex_t’ has no member named ‘visited’
error: ‘vertex_t’ has no member named ‘weight’
error: ‘vertex_t’ has no member named ‘prev’
Can anyone help me understand why I cant do this?
Okay so I can do it after the for loop in which I malloced it?
You'd do it better in the loop.
vertex_t *vertex[G->vertices];
for (i = 0; i < G->vertices; i++)
{
vertex[i] = malloc(sizeof(vertex_t));
vertex[i]->visited = 0;
vertex[i]->weight = FLT_MAX;
}
or according to Zeta's suggestion:
vertex_t vertex[G->vertices];
for (i = 0; i < G->vertices; i++)
{
vertex[i].visited = 0;
vertex[i].weight = FLT_MAX;
}

Resources