0

Drowning in trying to understand how to dereference pointers in a linked list here...

Let's say I have a simple struct, called entry, which has char * name and int ID entry* next fields.

If I know I'll have 10 of them, it seems like the way to go is to make an array of pointers to structs:

entry* ptrArray[10];

and then loop i = 0 -> 10

ptrArray[i] = malloc(sizeof(entry));

I am running into a bunch of issues dealing with getting things in and out of here.

To input characters I only need to dereference the pointer in the array using -> correct? eg

scanf("%s", ptrArray[i]->name);

Because the dereference here points to the block of memory of the start of the char * correct?

But if I want to put in a number, I need to use the & operator... eg

scanf("%d", &ptrArray[i]->ID);

Is this because the int doesn't point to the address so I need to fetch it?

Then if I want to link the list together in this array, could I loop through 0 -10 and for 1 through 9 do something like:

ptrArray[i]->next = ptrArray[i+1];

It seems like I should be able to because the array just has pointers to structs and I'm just adding one.

Now let's say I want to print these guys. Is it as simple as

printf("%s 's ID is %d", ptrArray[i]->name, ptrArray[i]->ID);

I'm having a ton of trouble understanding how the array number the -> notation and the * to dereference works in this situation. I thought I understood it but I apparently do not, since when I run code like this I get segfaults.

Thanks for any help.

1 Answer 1

1

It's a cruel trick by the evil computer!! It's likely that you do understand "all that stuff". The real problem may be scanf! I tried a little repro case, couldn't get it to work (it didn't prompt as expected) and asked Mr. Google what was wrong ("using scanf in a loop"). From this post (emphasis added):

The original code loops indefinitely because the invalid data (the "gfggdf") is not removed from the input buffer when scanf fails to convert it to an integer -- it's left in the input buffer, so the next call to scanf looks at the same data,

And from this one (which also includes many interesting links):

Also, I feel obligated to discourage you from using scanf entirely:

One option might be to use the cs50.h functions, ie GetString() and GetInt(), instead of scanf. Something like ptrArray[i]->name = GetString(); (which has the added bonus of allocating for you!) and ptrArray[i]->ID = GetInt();

And (hopefully) to clarify this:

scanf("%d", &ptrArray[i]->ID);
Is this because the int doesn't point to the address so I need to fetch it?

From man scanf (emphasis added):

The scanf() family of functions scans input according to format as described below. This format may contain conversion specifications; the results from such conversions, if any, are stored in the locations pointed to by the pointer arguments that follow format.

1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .