I have an integer array. And I want to fill the array with "custom numbers"
int arr[5]; // creat array
for (int i = 0; i < 5; i++) // head loop
{
printf("Enter Num: "); // print mesage
scanf("%d", arr+i); // ride num by index
}
After I sum up all the numbers in the array, I get an unexpected result. I couldn't figure out why for a long time until I added a line to the loop:
scanf("%d", arr+i);
printf("%d\n", arr[i]);
And then I noticed arr[0]
. After entering the second number, arr[0]
changed to 3041564. And changed in every cycle. And I still can't figure out why.
I didn't expect the first number in the array to change its value. And I found only one solution: create an array of 6 elements instead of 5 and do not touch the first element
Asked to attach code? Here is the full code:
#include <stdio.h>
void input(const char *, int *);
void add(char *, int, char *, int);
int main(int argc, char *argv[])
{
int num = 0;
int nums[5];
for (char i = 0; i < 5; i++)
{
char mes[1];
add("Num", 3, mes, i+1);
input(mes, &nums[i]);
}
int sum = 0;
for (char i = 0; i < 5; i++)
{
sum += nums[i];
}
printf("Sum: %d", sum);
return 0;
}
void input(const char *mes, int *num)
{
printf("Enter %s: ", mes);
scanf("%d", num);
}
void add(char *str, int len, char *newStr, int num)
{
for (int i = 0; i < len; i++)
{
*(newStr+i) = *(str+i);
}
*(newStr+len) = num+48;
}
Input: 4 4 4 4 4
The expected output: 20
The actual output: 37324350