realloc removing data already in array in C [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
For some reason when I reallocate the size of the array created using calloc it deletes the values that have already been inputted, maybe something else is happening but i don't understand why. I have changed the code so that it includes everything it needs to work, sorry i forgot about that
#include <stdio.h>
#include <stdlib.h>
int main(void) {
unsigned int arraySize; // size of array
int moreElements; // stores user input whether more elements are to be
int additionalElements = 0; // number of elements to be added to array
unsigned int type; // stores the type of array
float sum = 0; // the sum of the elements
float *floatArrPtr; // pointer to a flaot
floatArrPtr = calloc(arraySize, sizeof(float));
for(size_t i = 0; i < arraySize; i++)
{
printf("Please enter a number for the array: ");
scanf("%f", &floatArrPtr[i]);
printf("%f\n", floatArrPtr[i]);
}
for(size_t i = 0; i < arraySize; i++)
{
sum += *(floatArrPtr+i);
}
sum /= arraySize;
printf("The average of the elements of the array is %lf\n", sum);
do
{
printf("if there are more elements to be added enter 1 and 0 if not: ");
scanf("%d", &moreElements);
} while (moreElements != 0 && moreElements != 1);
if (moreElements == 1) {
printf("please enter the number of additional elements you want to add: ");
scanf("%d", &additionalElements);
floatArrPtr = realloc(intArrPtr,(arraySize+additionalElements) * sizeof(float));
for (size_t i = arraySize; i < arraySize+additionalElements; i++)
{
printf("Please enter a number for the array: ");
scanf("%f", &floatArrPtr[i]);
}
sum = 0;
for(size_t i = 0; i < arraySize+additionalElements; i++)
{
sum += *(floatArrPtr+i);
printf("%zu, %lf, %d\n", i, floatArrPtr[i], arraySize + additionalElements);
}
sum /= (arraySize + additionalElements);
printf("The average of the elements of the array is %lf\n", sum);
}
}

That calloc code at the top is wrong. For an arraySize of 1000 it allocates a million floats, or 4MB. Look that up.
Then I assume the real problem is the intArrayPtr that slipped in from earlier code.
Use functions, they pay off. – I mean make all your code no more than 4 lines or so long per function, this will stop old variables from earlier from slipping in.
The wrong line is
floatArrPtr = realloc(intArrPtr...
You need
floatArrPtr = realloc(floatArrPtr...
I don't know the purpose of intArrPtr, but it looks like if that code compiles that its coming in from code above.
You have global variables. One must be very careful with them as they are a pain at best, at worst they cause unforeseen edge case bugs, which is what you have.
Make your project two files, one for integer and one for float, and you will see your mistake in the compiler.

Related

Output the input Array in C [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
My code:
int main()
{
int menu[16];
int i;
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
printf("%d", menu[i]);
}
I'm trying to ask the user for input and add it to the array and then at the end to output the whole array e.g 1,2,3,4....16, however as of now it always returns the value 16 no matter what the user input.
You need to run loop twice. Once for taking inputs and then for displaying all numbers.
#include <stdio.h>
int main()
{
int menu[16];
int i;
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
for(i = 0; i < 16; i++)
{
printf("%d\n", menu[i]);
}
}
Your code has an array index bound check failure.
printf("%d", menu[i]);
The value of i here is going to be 16 because you are using it after the loop. The loop terminal condition is i == 16. The menu array is only defined for index values of [0..15]. The value you see in the output is entirely random depending on the state of the execution stack. You could test this by printing instead menu[65] and see random data or maybe a segmentation fault.
Printing out the array to the console is the same loop as your input, but with the printf embedded in it instead. So your code should have 2 loops in it. One loop to gather input, and the other loop to output the input.
The answer is in the comments.
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
for(i = 0; i < 16; i++)
printf("%d ", menu[i]);
you can add a loop at the end of your code like this
int main()
{
int menu[16];
int i;
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
for (i = 0;i<16;i++)
{
printf("%d ",menu[i]);
}
}
"I'm trying to ask the user for input and add it to the array and then at the end to output the whole array"
Just because it has not been suggested yet...
This can be done using a single loop, or with no loops at all.
(The looping option below is an adaptation of your code with comments describing differences.)
//The following items, are optionally
//defined here instead of in-line with code.
//they are used to clean up the scanf() and sprintf() calls below
#define data menu[0],menu[1],menu[2],menu[3],menu[4],menu[5],menu[6],menu[7],menu[8],menu[9],menu[10],menu[11],menu[12],menu[13],menu[14],menu[15]
#define input_data &menu[0],&menu[1],&menu[2],&menu[3],&menu[4],&menu[5],&menu[6],&menu[7],&menu[8],&menu[9],&menu[10],&menu[11],&menu[12],&menu[13],&menu[14],&menu[15]
const char input_format[] = {"%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d"};
const char format[] = {"%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d\n"};
//it also preferred to avoid magic numbers when possible
#define ELEMENTS 16
#define MAX_LEN_INT 11
//to demonstrate both looping and sequential methods to input and output the same thing
#define USE_LOOP 1 //change to zero for doing this with no loops
int main(void)//added void
{
int menu[ELEMENTS] = {0};
//char buffer `output` should accommodate room for max number of
//characters expressed in 32bit `int` data type: `11` (from the value: `-2147483648`)
//times count of elements to be output: ELEMENTS plus NULL terminator + punctuation.
//This should do it:
int size = ELEMENTS*MAX_LEN_INT+ELEMENTS + 1;
char output[size];//buffer for outputing final line showing user input values
memset(output, 0, sizeof(output));
#if USE_LOOP
int i;
printf("Input array values:\n");//moved outside the loop to display only once
for(i = 0; i < ELEMENTS; i++)
{
printf("enter value %d:\n", i+1);//prompt user for each input value
scanf("%d", &menu[i]);//scan value into array element
}
#else //Use sequential data entry
printf("Enter %d space delimited integer values (eg: 1 2 -45 78... 123) then <enter>:\n", ELEMENTS);
scanf(input_format, input_data);
#endif
//again, outside the loop to display only once
//place all data into printable buffer
sprintf(output, format, data);//using short representations of format specifier and data for readability
printf("%s", output);
return 0; //added return to comply with int function type.
}
Tested with largest possible number of digits using sequential method:

Adding 3 basic features to my existing code [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have a gradebook program that I've been building, which works fine, but now I want to slot 3 new functions into the existing code. I can't wrap my brain around the logical path I need to take to make it work. I need a SIMPLE way to also get the highest, lowest, and average grades printed at the end. Here's my program...
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_GRADE_COUNT 200
int main() {
int grade[MAX_GRADE_COUNT];
int i;
int count = 0;
char continueResponse;
printf("Welcome to Gradebooker!\n\n");
for(i = 0; i < MAX_GRADE_COUNT; i++) {
printf("Please enter grade (0-100): ");
scanf(" %d", &grade[i]);
count++;
printf("Do you have more grades to enter?(Y/N): ");
scanf(" %c", &continueResponse);
if(toupper(continueResponse) != 'Y') {
printf("\n >> Thank you for using Gradebooker! <<\n");
break;
}
}
printf("\n\nCurrent Gradebooker listings: \n\n");
for(i = 0; i < count; i++) {
printf("\t%5d\n", grade[i]);
}
return 0;
}
The program would need to calculate the max, min and average in the second loop, like this:
int sum = 0;
int minimum = INT_MAX;
int maximum = 0;
for(i = 0; i < count; i++) {
printf("\t%5d\n", grade[i]);
sum += grade[i];
if(grade[i] < minimum) minimum = grade[i];
if(grade[i] > maximum) maximum = grade[i];
}
float average = (float)sum / count;
printf("min grade: %d\n", minimum);
printf("max grade: %d\n", maximum);
printf("average: %f\n", average);
The minimum starts with a value that is larger than all values in the list (INT_MAX for example is the largest possible value an int can take). Then, for each grade in the array, it replaces it with that grade, if it is smaller than the one currently in the minimum variable. That way minimum will in the end contain the smallest grade.
Same for maximum, but reversed.
For the average, it accumulates the sum of all grades (sum needs to be initialized to 0 at the beginning), and the divides it by the number of grades in the end. This gives an arithmetic mean in average.
Using float, it calculates the average as a floating point number (so the average can be non-integer). The (float)sum / count is needed so that it will first cast (convert) sum to a float, and so a floating point division on it. Otherwise, with sum / count is would do an integer division (which returns a rounded down integer), and store that as float in the average variable afterwards.
The idea for finding maximum value is: first declare a variable (lets say, MAXX) to store maximum value and initial it with as minimum value as possible and then iterate through the array and if any value in the array found greater then the current value of MAXX variable than update the value of MAXX with the value.
The idea for finding minimum value is: first declare a variable (lets say, MINN) to store minimum value and initial it with as maximum value as possible and then iterate through the array and if any value in the array found greater then the current value of MINN variable than update the value of MINN with the value.
Idea for finding avarage: Sum all the grade and then divide the sum with the number of grade.
See the implementation below for better understanding:
int max_grade = 0;//for storing maximum grade
/*
Minimum possible value should be initialize here.
Best option to write here is:
int max_grade = INT_MIN;
But to use INT_MIN <limits.h> file must be included.
*/
int min_grade = 10000000;//for storing maximum grade
/*
Maximum possible value should be initialize here.
Best option to write here is:
int min_grade = INT_MAX;
But to use INT_MAX <limits.h> file must be included.
*/
int total_grade = 0;//for counting all the grade
for(i = 0; i < count; i++) {
if(grade[i] > max_grade){
max_grade = grade[i];
}
if(grade[i] < min_grade){
min_grade = grade[i];
}
total_grade += grade[i];
}
printf("Max grade = %d\n" max_grade);
printf("Min grade = %d\n" min_grade);
printf("Avg grade = %d\n" total_grade/count);
I could not see all your code (it seemed to be cut off at the bottom), however the basically procedure to get an average, max and min in C is as follows:
int running_total = 0;
int count_grades = 0;
int max_so_far = 0;
int min_so_far = 999;
while( -1 ){ // infinite loop
// get input (a grade)
// if input is done, break
count_grades++;
running_total += iCurrentGrade; // (iCurrentGrade should be defined during input phase)
if( iCurrentGrade > max_so_far ) max_so_far = iCurrentGrade;
if( iCurrentGrade < min_so_far ) min_so_far = iCurrentGrade;
}
printf( "avg: %d min: %d max: %d\n", (int)(running_total / count_grades), min_so_far, max_so_far );

Take user input and continue to use it's variable throughout [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Not doing anything special. Just taking a user's input between 1 - 500, and then printing the number using for loop for each iteration. It crashes at the for loop. It does not print anything at all.
#include <stdio.h>
int forCounter() {
int num;
int count = 0;
printf("Pick a positive number (1 - 500): ");
scanf("%d", &num);
while (num < 1 || num > 500) {
printf("Out of range, try again (1 - 500): ");
scanf("%d", &num);
}
int i = num;
for (i; count <= i; count++) {
printf(count);
}
getchar();
return 0;
}
I take first input applied to 'num' and check if it's above or below allowed amount with the while loop.
When that's done it leaves and should start the for loop with i taking over for num. I tried using num in the place of i but it didn't work so I tried using a separate variable to see if it'd work.
I get two warnings seen in the image providedTwo warnings
You have to specify the format of output in printf.
int printf(const char *format, ...)
Your code:
#include <stdio.h>
int forCounter(void) {
int num;
printf("Pick a positive number (1 - 500): ");
scanf("%d", &num);
while (num < 1 || num > 500) {
printf("Out of range, try again (1 - 500): ");
scanf("%d", &num);
}
for (int i = 1; i <= num; i++) {
// printf(count); --> Bad
printf("Value = %d\n", i);
}
getchar(); // this will return immediately
return 0;
}

I have to find two smallest numbers without arrays [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
So basicly I have this assignement in C, I have to input numbers until I enter 0, and after I enter 0 I have to print 1st and 2nd min number from all that numbers and I can't use arrays. I get that I have to use do-while loop for input but I can't figure out how to find two smallest from all of them. I think that thing can be done with if loops but don't know how to make it as I have only one variable to enter numbers into it (int a). And in input I have error when I enter 0 I'm able to enter one more number before program quits.
#include <stdio.h>
int main() {
int a;
do {
printf("Enter numbers: ");
scanf("%d\n", &a);
//what to do here
}while(a != 0);
You need to add 2 variables to hold the smallest values detected so far. Like
int smallest = INT_MAX;
int second_smallest = INT_MAX;
Then in the loop you need to test if the new input value is smaller than the values stored so far. Something like:
if (a <= smallest)
{
second_smallest = smallest;
smallest = a;
}
else if (a < second_smallest)
{
second_smallest = a;
}
You can use two variables to do what you need
#include <stdio.h>
#include <limits.h>
int main(void)
{
int a = INT_MAX;
int min_1 = INT_MAX;
int min_2 = INT_MAX;
int valid;
do
{
if (a < min_1)
{
min_2 = min_1;
min_1 = a;
}
else if (a < min_2)
{
min_2 = a;
}
printf("Enter numbers: ");
valid = scanf("%d", &a);
}
while ((a != 0) && (valid == 1));
if (valid == 1)
{
printf("Minimum numbers entered are: %d %d\n", min_1, min_2);
}
else
{
fprintf(stderr, "Error in data input\n");
}
}
So:
use limits.h defines to init min variables to the highest value for int type INT_MAX.
for each loop you must test if entered number is a minimum
you must check that user input is valid: check scanf return value.
remove \n in the format string of scanf.

Printing garbage value instead of maximum value from an array in c [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm a newbie in programming.
I've tried this code to find out the maximum value in an array. I've also drawn the logic of this code on paper & it's coming out valid.
I'm wondering why this code is printing garbage value instead of max value.
Here is the code:
void main(){
int size, i, max=0;
printf("Enter the size of the array:\n");
scanf("%d", &size);
int a[size];
printf("Enter the elements:\n");
for(i=0; i<size; i++){
scanf("%d", &a[i]);
}
for(i=0; i<size; i++){
if(a[i]<a[i+1]){
max=a[i+1];
}
}
printf("\nMax value is %d", max);
}
You can try this code..
int main(){
int size, i, max=0;
printf("Enter the size of the array:\n");
scanf("%d", &size);
int a[size];
printf("Enter the elements:\n");
for(i=0; i<size; i++){
scanf("%d",&a[i]);
}
// Search Max Value
max = a[0];
for (i = 0; i < size; i++)
{
if (a[i] > max)
{
max = a[i];
}
}
printf("\nMax value is %d", max);
return 0;
}
You need to initialize max somewhere prior to searching the array (which the current copy of the post does do ... but the first one did not). However, if negative values are entered, it probably makes sense to use INT_MIN.
max = INT_MIN;
And then you need to compare the current max value against the array elements (rather than the array elements against themselves.
At this point, in your code, you're going outside of your array. You're also not comparing the element of the array to the current max, but to the next element in the array. This would be for sorting an array, but not finding the maximum value.
for(i=1; i<=size; i++){ /* i<=size */ you go one beyond
if(a[i]<a[i+1]){ /* when i==size, you're 2 outside of your array */
max=a[i+1];
}
}
You can have i<(size-2), but it's not very pretty.
You can also set max to the first element of the array, and loop from the second element.
max = a[0];
for(i=1 ; i<size ; i++){ /* loop to the end of the array */
if(a[i] > max){ /* compare current space to max */
max = a[i];
}
}
main has return type int, always. Valid prototypes:
int main()
int main(int argc, char* argv[])
Starting with 0 as initial value for maxinstead of INT_MIN means you have an implicit element of value 0.
Always test the return value of scanf, it might not succeed.
Your second loop tries reading a[size] and a[size+1], while your array only goes to index size-1.
Correct the termination condition to <.
Correct the comparison to compare a[i] with max.

Resources