I have checked the other questions with similar problems, but none of the solutions worked for my case.
The problem in hand is, I am trying to create a stack with dynamic memory, using this struct:
struct stekas{
int content;
struct stekas *link;
} *top = NULL;
However, I'm running into trouble in a few of my functions: Specifically, "Dereferencing pointer to incomplete type". Here's the erroneous pieces of code:
struct node *temp;
temp = (struct stekas*)malloc(sizeof(struct stekas));
/* some code */
temp = top;
printf("Popped out number: %d\n", temp->content);
top = top->link;
free(temp);
And here's the other function that gets the error:
int i;
struct node *temp;
/* some code */
for (i = top; i >= 0; i--) {
printf("%d\n", temp->content[i]);
I'm assuming it has something to do with the pointer not connecting to the content. I've checked other questions, they seemed to have poblems with the struct itself, but I personally don't see any problems with this one.
It seems that the struct node
used in these code snippets
struct node *temp;
temp = (struct stekas*)malloc(sizeof(struct stekas));
/* some code */
temp = top;
printf("Popped out number: %d\n", temp->content);
top = top->link;
free(temp);
and
int i;
struct node *temp;
/* some code */
for (i = top; i >= 0; i--) {
printf("%d\n", temp->content[i]);
was not defined.
I think you mean struct stekas
Also the both code snippets have other serious errors. For example you allocated memory and assigned its addres to pointer temp
temp = (struct stekas*)malloc(sizeof(struct stekas));
/* some code */
and then overwrote the pointer. So the address of the allocated memory is lost.
temp = top;
So there is a memory leak.
Or in this statement
for (i = top; i >= 0; i--) {
variable i has type int while top is a pointer. So this assignment i = top and this decreasing i-- does not make sense.
And whet about expression temp->content[i]
used in the printf statement?
printf("%d\n", temp->content[i]);
content
is neither a pointer nor an array. So you may not apply the subscript operator.
The problems as I see here are
struct node
is not defined is the scope it is used. Maybe struct node
is meant to be struct stekas
.
printf("%d\\n", temp->content[i]);
content
is not an array or pointer that can be de-referenced.
That said,
free()
the allocated memory to temp
before temp = top;
, to avoid memory leak. Also, please do not cast the return value of malloc()
and family in C
.
temp = top;
top
is null and you are making temp
point to null and dereference it which will lead to undefined behavior.
You malloc()
would have given you memory which you can access so use it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.