与指针,数组和stdin明显混淆

时间:2014-11-25 08:31:06

标签: c arrays pointers stdin

我试图读取N行的两列float。下面的代码是我想出的,不幸的是输出不是我的预期。我认为问题可能源于指针使用不当。输入和输出遵循代码。

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 

1 个答案:

答案 0 :(得分:2)

指针的用法很好。但是在打印实际读取的值之前,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;
}