Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning values to a key in a pointer to a record in C

Tags:

c

pointers

struct

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 :)

like image 991
Paul Ruiz Avatar asked Mar 29 '12 02:03

Paul Ruiz


People also ask

How do you assign a value to a pointer to a variable?

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.

Can we assign value to a pointer?

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.


1 Answers

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);

like image 105
Cornstalks Avatar answered Sep 22 '22 19:09

Cornstalks