c - 与指针、数组和标准输入明显混淆

标签 c arrays pointers stdin

我正在尝试读取两列 float 的 N 行。下面的代码是我想出的,不幸的是输出不是我所期望的。我相信问题可能源于指针使用不当。输入和输出遵循代码。

int main (void){
  int i = 0;
  int initSize =10;
  double *xptr = (double *)calloc(initSize, sizeof(double));
  double *yptr = (double *)calloc(initSize, sizeof(double));

  while((scanf(" %lf %lf", &xptr[i], &yptr[i])) != -1){
    i++;
    if( i == initSize){
      initSize *=2;
      double *xtemp = xptr;
      double *ytemp = yptr;
      xptr = (double *)calloc(initSize, sizeof(double));
      yptr = (double *)calloc(initSize, sizeof(double));
      memcpy(yptr, ytemp,sizeof(double));
      memcpy(xptr, xtemp,sizeof(double));
    }
    printf("x =  %lf y =  %lf \n", xptr[i] , yptr[i]);
  }
}

输入:

-150.5    127 
-98.76453 0.901
100.1     140.34
128       59.08765    
0.0039    -.000256
3.5       1.1
1.54      1000.987

输出:

x =  0.000000 y =  0.000000 
x =  0.000000 y =  0.000000 
x =  0.000000 y =  0.000000 
x =  0.000000 y =  0.000000 
x =  0.000000 y =  0.000000 
x =  0.000000 y =  0.000000 
x =  0.000000 y =  0.000000 

最佳答案

您的指针的使用很好。但是 i 在打印实际读取的值之前递增。 这可以通过使用 realloc() 的 2 个指针来完成,如下所示。

int main (void){
   int i = 0,j;
   double *temp;
   double *xptr = malloc(sizeof(double));
   double *yptr = malloc(sizeof(double));

   while((scanf(" %lf %lf", &xptr[i], &yptr[i])) == 2){ 

      printf("x =  %lf y =  %lf \n", xptr[i] , yptr[i]);
      temp = realloc(xptr,sizeof(double) * (i+2));
      if(temp == NULL)
      {
         printf("Memory allocation failed\n");
         break;
      }
      else
         xptr = temp;
      temp = realloc(yptr,sizeof(double) * (i+2));
      if(temp == NULL)
      {
         printf("Memory allocation failed\n");
         break;
      }
      else
         yptr = temp;
      i++;
   }   
   printf("Out\n");
   for(j=0;j<i;j++)
      printf("%lf %lf\n",xptr[j],yptr[j]);
   free(xptr);
   free(yptr);
   return 0;
}

关于c - 与指针、数组和标准输入明显混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27121871/

相关文章:

c - 从结构访问双指针并在 execvp 中使用它

c - Socket编程C【发送消息给选定的客户端】

python - 如何按列对多维数组进行排序?

arrays - Swift indexOf 不一致的行为

c - 有多大的结构可以有效地按值传递?

c - 指针问题

c - C 中使用数组的大整数

c - 如何防止符号重新定义

arrays - Julia:如何从数组中选择整行

C错误: Initialization From Incompatible Pointer Type