0

I am trying to collect user data for a priority queue in C. When I have a loop that does multiple scanf's to collect input. My problem is, that when I eventually pop my values from my queue. All items are the same value. Here's my example:

queue_t *q = create();

//The count is just a temporary solution to a break condition.
//Just used for testing

int count = 0;
while(1){

    printf("\nPlease Enter A Task: \n");
    char* a;
    scanf("%s", &a);

    printf("\nPlease give your task a priority ranking between 0-(less important) and 10-(most important) : \n");
    int rank;
    scanf("%d", &rank);

    item_t item;
    item.value = &a;
    item.rank = rank;

    insert(q, item);
     count++;

     if(count == 5)
        break;
}

So this loops 5 times. If I entered: test1, test2, test3, test4, test5. When it eventually pops and prints in later code, it prints: test5 test5 test5 test5 test5

How can I effectively have a loop to collect input without overwriting the address of a previous input? (if that's what the problem is)

and my struct is:

typedef struct i {
void *value;
float rank;
} item_t;
KrispyK
  • 235
  • 6
  • 18
  • This code would work (modulo the fact that `scanf` should never be used) if `insert` copied the `item` object. The behavior you are seeing suggests that it does not, and in fact that you may be saving pointers to the stack into the heap, which is asking for memory corruption. Without seeing the rest of the code I cannot be more specific. – zwol Mar 27 '14 at 02:54

2 Answers2

1

To solve your problem, item.value should be allocated then written to

while(1) {

    printf("\nPlease Enter A Task: \n");
    item_t item;
    item.value = (char *)malloc(100);
    // scanf("%s", item.value);
    fgets(item.value, sizeof (item.value), stdin);

    printf("\nPlease give your task a priority ranking between 0 -(less important) and 10-(most important) : \n");
    scanf("%f", &item.rank);

    insert(q, item);
    count++;

     if(count == 5)
        break;
}
smac89
  • 39,374
  • 15
  • 132
  • 179
0

If you use char *a, you have to allocate memory for it. Otherwise use char a if your input is a single character.

You also have to copy the value in a to item.value. item.value should have memory allocated before you copy.

Dinesh
  • 2,194
  • 3
  • 30
  • 52