C语言malloc函数问题

#include<stdio.h>#include<stdlib.h>int main (void){ double * ptd; int max; int number; int i=0;
puts("What is the maximum number of type double entries?"); scanf("%d",&max); ptd = (double * )malloc(max * sizeof(double)); if(ptd == NULL) { puts("Memory allocation failed.Goodbye."); exit(EXIT_FAILURE); } //ptd现在指向有max个元素的数组 puts("Enter the values(q to quit):"); while(i<max && scanf("%lf,&ptd[i]")==1) ++i; printf("Here are your %d entries:\n",number = i); for(i = 0;i < number;i++) { printf("%7.2f",ptd[i]); if( i%7 == 6) putchar('\n'); } if(i % 7!=0) putchar('\n'); puts("Done."); free(ptd);
return 0;}

#include<stdio.h>
#include<stdlib.h>
int main (void)
{
 double * ptd;
 int max;
 int number;
 int i=0;

 puts("What is the maximum number of type double entries?");
 scanf("%d",&max);
 ptd = (double * )malloc(max * sizeof(double));
 if(ptd == NULL)
 {
  puts("Memory allocation failed.Goodbye.");
  exit(EXIT_FAILURE);
 }
 //ptd现在指向有max个元素的数组
 puts("Enter the values(q to quit):");
 while(i<max && (scanf("%lf",&ptd[i])==1))//这句scanf中的分号位置错了
 ++i;
 
 printf("Here are your %d entries:\n",i);//这句建议最好不要把赋值和输出写在一起,最好分开写便于理解
 number = i;
 for(i = 0;i < number;i++)
 {
  printf("%7.2f",ptd[i]);
  if( i%7 == 6)
   putchar('\n');
 }
 if(i % 7!=0)
  putchar('\n');
    puts("Done.");
    free(ptd);

    return 0;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-10-01
i<max && scanf("%lf,&ptd[i]")==1
&&是短路求值,当i<max时不会执行scanf("%lf,&ptd[i]")==1,另外这个scanf本身就是错的
第2个回答  2013-10-01
需要加一个malloc.h的头文件,即#include<malloc.h>
相似回答