0

I desire that my programm makes the user input numbers into a dynamic array and if the user type -1, it will stop asking for more numbers. The problem here is probably the condition in my while, that's where I have my doubts.

int i=0, size=0;
float *v;
printf("Write a group of real numbers. Write -1 if you want to stop writing numbers\n");
v=(float*)malloc(size*sizeof(float));
while(v!=-1)
{

    printf("Write a number\n");
    scanf("%f", &v[i]);
    i++;
    size++;
    v=realloc(v, (size)*sizeof(float));

}
0

2 Answers 2

1

size=0; starts with a 0-length array which you write into out-of-bounds with scanf("%f", &v[i]); before incrementing size. The same out-of bounds write happens on every iteration. I rewrote like this. Note there is no initial malloc because realloc will work when given a NULL pointer.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int size = 0, i;
    float *v = NULL;
    float val;
    printf("Write a group of real numbers. Write -1 if you want to stop writing numbers\n");
    printf("Write a number\n");
    while(scanf("%f", &val) == 1 && val != -1)
    {
        v = realloc(v, (size+1) * sizeof(float));
        v[size++] = val;
        printf("Write a number\n");
    }

    printf("Results\n");
    for(i=0; i<size; i++)
        printf("%f\n", v[i]);
    free(v);
    return 0;
}

Program session:

Write a group of real numbers. Write -1 if you want to stop writing numbers
Write a number
1
Write a number
2
Write a number
3
Write a number
-1
Results
1.000000
2.000000
3.000000
Sign up to request clarification or add additional context in comments.

Comments

0

Instead of comparing v with -1, you probably want to compare v[i - 1] with -1. Also, you should perform error checking for when scanf couldn't parse a number:

do {
    printf("Write a number\n");
    if (scanf(" %f", &v[i]) != 1) {
        /* error handling here */
    }

    v = realloc(v, size * sizeof *v);
    if (v == NULL) {
        /* error handling here */
    }
} while (v[i++] != -1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.