【发布时间】:2017-02-07 18:40:12
【问题描述】:
我正在尝试创建一个动态浮点数组。用户应键入值,直到找到负值。然后在屏幕上显示数组。由于我不知道数组的大小,所以每次输入有效值时,我都会使用 realoc() 来增加数组的大小
我的代码为所有元素分配内存,但是当我打印数组时,出现分段错误。不知道是我赋值错误还是读取失败。
代码如下:
#include <stdio.h>
#include <stdlib.h>
unsigned int createArray(float*);
void printArray(float *, unsigned int);
int main(){
float *pArray = NULL;
unsigned int arrayLength = 0;
arrayLength = createArray(pArray);
printArray(pArray, arrayLength);
return 0;
}
/**
* Ask the user to fill an array untill he types a negative value
*
* @param A pointer to the array we want to create
* @return The final length of the array
*
*/
unsigned int createArray(float *pArray){
float number = 1;
int arrayLength = 0;
while(number>0){
printf("\nSetting number %d: ", arrayLength);
scanf("%f", &number);
arrayLength++;
pArray=realloc(pArray, sizeof(float)*arrayLength);
if(pArray==NULL){
printf("\nERROR: Not enough memory");
free(pArray);
exit(0);
}
pArray[arrayLength-1] = number;
}
return arrayLength;
}
/**
* Prints an array given by the user
*
* @param Pointer to the array
* @param Length of the array
*
*/
void printArray(float *pArray, unsigned int arrayLength){
for(int i=0;i<arrayLength;i++){
printf("\nItem[%d]: %.2f", i, *pArray+i);
}
}
【问题讨论】:
-
动态数组的处理方式与静态或自动数组的处理方式不同。
-
free(NULL)有什么意义? -
Touché,没有意识到这一点。
-
行:
while(number>0)不同意该问题也不同意用户提示。那是因为 0 不是负数,而是从有效输入值中排除,所以会导致循环退出。建议:while(number>=0.0f) -
在编写
float文字时,数字必须包含小数点和尾随f。没有小数点,数字是整数,而不是浮点数。没有尾随的f,数字是double,而不是float