1. ## Finding LinkedList Size

I'm simply trying to find the length of the linked list, but my findSize() function isn't working right and I'm not sure where it's going wrong...I get a segmentation fault when i run it, so probably out of bounds somewhere...just where?

Code:
```typedef struct node {
char* value;
struct node* next;

int main() {

char str1[] = {'t', 'e', 's', 't', '\0'};

LinkedList* ll = llCreate();

int* size;
findSize(ll, size);
printf("%d", *size);

}

void findSize(LinkedList* ll, int* size) {
LinkedList* p = ll;

while(p != NULL){
(*size)++;
p = p->next;
}
}

return NULL;
}

nn->value = value;

if (*ll == NULL) {
*ll = nn;
} else {
// General case - find the end
LinkedList* p = *ll;
while (p->next != NULL) {
p = p->next;
}
p->next = nn;
}
}```

2. If size in main() is a pointer, what is it pointing to?

3. I would say he is confused with the fact that you have to pass a variable by reference, so that the modification remains after the function terminates.

You should declare the variable as just an int and call the function like this
Code:
`findSize(ll, &size);`
Your function is nice, it works

But, there is a logical error there, isn't?
You increment your variable, but which is its initial variable? Initialize it to zero and you would be fine

4. Originally Posted by std10093
I would say he is confused with the fact that you have to pass a variable by reference, so that the modification remains after the function terminates.

You should declare the variable as just an int and call the function like this
Code:
`findSize(ll, &size);`
Your function is nice, it works

But, there is a logical error there, isn't?
You increment your variable, but which is its initial variable? Initialize it to zero and you would be fine

That fixed the segmentation fault, thank you, but now my size is only incrementing to 1 and then not looping through the while loop

5. I would guess the problem is at your list. Did you print the list and prints the whole list?

6. Originally Posted by std10093
I would guess the problem is at your list. Did you print the list and prints the whole list?
huh, where?? The while loop in my findSize() function is only going through once

7. From your code above, 1 would be the correct value. You only add one node to your list.

You should always check your pointer to malloc'd memory for NULL before attempting to use it.

LinkedList is a misleading name for a node struct. Is a struct a linked list?

8. Originally Posted by Tclausex
From your code above, 1 would be the correct value. You only add one node to your list.

You should always check your pointer to malloc'd memory for NULL before attempting to use it.

LinkedList is a misleading name for a node struct. Is a struct a linked list?
Oops, forgot it is a string not a bunch of characters it is reading in, i just tested with multiple strings and it works, thanks!

Popular pages Recent additions