Pregunta

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;
¿Fue útil?

Solución

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

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top