I just have a quick question.
Say I have a struct for the purpose of commenting in which it could be filled up or left blank depending on the user. Therefore, I need to dynamically allocate memory to the array comments.
typedef struct userComments {
char comments;
} name;
So, what I’d do is to define 2 pointers: one to allow for pointing to the current record in the list, and the other to dynamically allocate memory to the char comments.
name *currentC, *comments;
In the main() section of the code, I would perform a malloc()
comments = (name *)malloc(sizeof(name));
However, subsequently, if I wanna get user comments, say from the below function:
void modifyComments() {
printf(“Update Comment: “);
gets(currentC->comments);
}
Visual Studio 2010 prompts an error message at this point, stating that:
Name *currentC;
Error: argument of type “char” is incompatible with parameter of type “char *”.
Had I assigned it statically, i.e.
typedef struct userComments {
char comments[40];
} name;
I would not encounter this problem.
I’m curious as to where I have gone wrong in my “accessing/updating” the array within the struct dynamically.
My lecturer told me this:
One way to overcome this is to give gets() access to a temporary char[], and then strcpy the result into the memory allocated and tracked by the pointer <comments>.
So, what I did was:
void modifyComments() {
char commentsTmp[40];
printf(“Update Comment: “);
strcpy(comments, gets(commentsTmp));
}
Now for the comments part (highlighted in red),
Visual Studio 2010 prompts the error:
Error: argument of type “name *” is incompatible with parameter of type “char *”
Did I do this correctly, or am I still making a mistake somewhere?