Reputation:
Here is my code:
void pwd(Fs_sim *files) {
Node *curr_node = files->curr;
Node **space = NULL;
int i = 0;
while (curr_node->parent != NULL) {
space = realloc(space, sizeof(Node *) * (i + 1));
*space + i = curr_node;
i++;
curr_node = curr_node->parent;
}
if (i == 0)
printf("/\n");
else {
while (i > 0) {
printf("/%s", (*space + i--)->name);
}
printf("\n");
}
free(space);
}
'space' is a pointer to an array that's being dynamically allocated. As each node being iterated through, I'd like to store a pointer to that node in the dynamically allocated array, and keep a count of how many elements there are. I get the error message:
error: lvalue required as left operand of an assignment
on the '*space + i = curr_node;' line.
I don't see what's wrong with it. Can someone clarify?
UPDATE:
I have changed the code and it now compiles, but I get segmentation fault when I run the executable. Here's my code:
void pwd(Fs_sim *files) {
Node *curr_node = files->curr;
Node **space = NULL;
int i = 0;
while (curr_node->parent != NULL) {
space = realloc(space, sizeof(Node *) * (i + 1));
*(space + i) = curr_node;
i++;
curr_node = curr_node->parent;
}
if (i == 0)
printf("/\n");
else {
while (i >= 0) {
printf("/%s", (*(space + (i-1)))->name);
i--;
}
printf("\n");
}
free(space);
}
still can't find what's wrong with it.
Thanks ahead of time. Big noob to C here.
Upvotes: 0
Views: 84
Reputation: 43138
The error I believe is here:
while (i >= 0) {
printf("/%s", (*(space + (i-1)))->name);
i--;
}
What happens when i
is 0 and you try to do (*(space + (i-1)))->name);
?
You get space + -1
!
Upvotes: 1
Reputation: 185
Pre-update answer:
You appeared to have flipped it around, it should be curr_node = *space + i
. It's because the variable whose value of an expression that you want to assign should be on the left, as you can't assign curr_node
into a sum of two variables
It that isn't quite right for your purpose, you can also do *(space + i) = curr_node
Upvotes: 1