Sorry if the title is a little confusing. What I'm doing is creating a structure such as:
struct record
{
int value;
int key;
};
Then using a typedef to call a pointer to record "Item" like this:
typedef struct record* Item;
Basically I'm following how it was done in Algoriths in C by Robert Sedgewick (third edition) on page 290 in case anyone happens to have this book.
What I'm having trouble with is reading in a value from the console, then assigning that to the key. Here's what I have, and the errors that I'm getting:
void setKey(Item *element, int x)
{
element->key = x;
}
void standInput(Item A[], int length)
{
int i;
int x;
for(i = 0; i < length; i++)
{
printf("Enter a value for spot %i: ", i+1);
scanf("%d", &x);
setKey(A[i], x);
}
}
gcc Item.h
Item.h:33:6: warning: conflicting types for ‘setKey’
Item.h:23:3: note: previous implicit declaration of ‘setKey’ was here
If I could get a nudge in the right direction, I'd really appreciate it. I got the program for this assignment working perfectly when Item was just simple ints, but now I'm trying to use Item->Key and I'm a little lost :) Thanks!
If anyone needs any other portion of the code that I didn't think necessary, I'll post it as soon as I see the request.
Revision: I moved my setKey function above standInput, so the compilation error has gone away. What I am getting though is a segment fault, so I'm still assigning it wrong :)
You need to initialize a pointer by assigning it a valid address. This is normally done via the address-of operator (&). The address-of operator (&) operates on a variable, and returns the address of the variable. For example, if number is an int variable, &number returns the address of the variable number.
You can assign a value to a void pointer, but you must cast the variable to point to some specified type before you can dereference it. Pointer arithmetic is also not valid with void * pointers.
setKey
takes a pointer to an Item
. A[i]
is not a pointer to an Item
, but an actual Item
object.
To pass it as a pointer do either:
setKey(A + i, x);
or
setKey(&A[i], x);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With