我怎么能修复这个数组

时间:2023-01-29 12:23:15

Good morning, I was trying to fill a dynamic vector but when I print the input data i get something like this:

早上好,我试图填充动态矢量,但是当我打印输入数据时,我会得到这样的结果:

input: 1,5,3,4,2
output: 0,1,5,3,4

Could somebody help me? I can't fix it. I've been trying a lot and can't get it. I'll apreciatte so much (sorry for the english)

有人能帮助我吗?我无法解决它。我一直在努力,无法得到它。我会非常感谢(对不起英语)

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

#define MAX_STR 10

int vecto();

char seguir[MAX_STRLEN];
int var;

float* vector; 
char* bv;

int vecto(){
int cont=0,ch;
char v[MAX_STR];
printf ("¿number of elements to order?: ");
scanf("%d",&var);
vector = (float*)malloc(var*sizeof(float));
while((ch = fgetc(stdin)) != EOF && ch != '\n' ){};

printf("input number press f for finish \n");
    do{
        fgets(v,sizeof(v),stdin);
        if((strcmp(v,"f")!=0)){
            cont++;
            vector[cont]=strtod(v,&bv);
        }
    } while(!((cont==var) || (strcmp(v,"f")==0)));
printf("\n");
return 0;
}

2 个解决方案

#1


1  

You increment cont before you set the value.

在设置值之前增加cont。

Just swap the order

只需交换订单

if((strcmp(v,"f")!=0)){
            vector[cont]=strtod(v,&bv);
            cont++;
        }

#2


1  

You increment the cont and after that you use it. So first time it access the index 1 instead of 0.

你增加cont,然后你使用它。所以第一次访问索引1而不是0。

Change it to:

将其更改为:

if((strcmp(v,"f")!=0)){
   vector[cont++]=strtod(v,&bv);
}

#1


1  

You increment cont before you set the value.

在设置值之前增加cont。

Just swap the order

只需交换订单

if((strcmp(v,"f")!=0)){
            vector[cont]=strtod(v,&bv);
            cont++;
        }

#2


1  

You increment the cont and after that you use it. So first time it access the index 1 instead of 0.

你增加cont,然后你使用它。所以第一次访问索引1而不是0。

Change it to:

将其更改为:

if((strcmp(v,"f")!=0)){
   vector[cont++]=strtod(v,&bv);
}