I'm trying to create a dynamic float array. The user should type values untill a negative one is found. Then show the array in the screen. As I dont know the size of the array, everytime a valid value is entered I use realoc() to increment the size of the array
My code allocates memory for all the elements, but when I print the array, I get a segmentation fault. Don't know if I assign values in a wrong way or fail while reading them.
Here is the code:
#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)?while(number>0)does not agree with the question nor the user prompt. That is because 0 is not negative, but is excluded from the valid input values, so will cause the loop to exit. suggest:while(number>=0.0f)floatliterals, the number must contain a decimal point AND a trailingf. With out the decimal point, the number is an integer, not a float. With out the trailingfthe number is adouble, not afloat