-2

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

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
HardTaker
  • 1
  • 1
  • Welcome, please a [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example), the shortest *complete* code that shows the problem. And post the inputs, the expected output and the actual output. May I suggest you take the [Tour](https://stackoverflow.com/tour) and read [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – Weather Vane Aug 16 '23 at 19:59
  • @HardTaker There is nothing wrong with the provided code. – Vlad from Moscow Aug 16 '23 at 20:00
  • Please [edit] your question to include a [mre]. Your code should be such that we can copy-paste and run it without needing to write additional code or make modifications. Please also comment on what input you're providing to stdin. – Brian61354270 Aug 16 '23 at 20:00
  • 2
    If you provide bad input to stdin, `scanf` will fail to read a number. You should check the return value of `scanf` to see if that happened – Brian61354270 Aug 16 '23 at 20:03
  • What are you typing? What delimiter do you have between the numbers? – Barmar Aug 16 '23 at 20:07
  • The snippet you posted first is not a part of the supposed "full code" – klutt Aug 16 '23 at 20:11
  • That is... substantially different from your original snippet. And looks to have at least one obvious buffer overflow... – Shawn Aug 16 '23 at 20:12
  • @Brian61354270 I kind of checked the output of scanf() and after the first input everything is correct, but after entering the second input, the value of the first element begins to change – HardTaker Aug 16 '23 at 20:17
  • @Barmar by number per iteration, separator: line break – HardTaker Aug 16 '23 at 20:18
  • You may be interested in [Why should I always enable compiler warnings?](https://stackoverflow.com/q/57842756/11082165). The minimum set of warning flags you should include is `-Wall -Wextra -pedantic-errors`. Your code compiles with several warnings. – Brian61354270 Aug 16 '23 at 20:20
  • You should maybe consider deleting this question, and posting a new one with your actual code and a description of the problem. This is very misleading with the "fake" code at the start. – pmacfarlane Aug 16 '23 at 20:21
  • @HardTaker You need to check the _return value_ of `scanf`, not the receiving arguments. – Brian61354270 Aug 16 '23 at 20:22
  • @HardTaker How is the appended code with undefined behavior related with the original code in the question?!!! – Vlad from Moscow Aug 16 '23 at 20:22
  • @pmacfarlane Why delete it and post a new one? There's no answers to this question yet. There's no reason the OP can't edit it as they see fit. Deleting this question and not improving it would increase the chance of them getting question banned. – Brian61354270 Aug 16 '23 at 20:22
  • @Brian61354270 Fair enough, but they should delete the misleading code segments at the start of the question. – pmacfarlane Aug 16 '23 at 20:23
  • @Brian61354270 It will be a lesson to write clear questions with minimal reproduciable programs. As for this question then it should be down-voted and closed. – Vlad from Moscow Aug 16 '23 at 20:25
  • `add("Num", 3, mes, i+1);` is overflowing the bounds of the `mes` array, causing undefined behavior. – Barmar Aug 16 '23 at 20:28
  • `add()` doesn't add a null terminator to `str`. – Barmar Aug 16 '23 at 20:29
  • @Barmar If I understand correctly what you are asking, then scanf() always returns 1 – HardTaker Aug 16 '23 at 20:30
  • You already answered my question earlier when you said you put newlines between them. What question are you answering? – Barmar Aug 16 '23 at 20:35
  • But the reason you're getting that strange output is because of the problem with `add()`. You need to make `mes` big enough to hold the string you're creating. – Barmar Aug 16 '23 at 20:35
  • @Barmar Danke schön. I didn't think that going beyond the limits would affect the result so much – HardTaker Aug 16 '23 at 20:37
  • Instead of that loop you can use `sprintf(newStr, "%s%d", str, num);` – Barmar Aug 16 '23 at 20:37
  • Buffer overflow is one of the most eggregious mistakes you can make in C. – Barmar Aug 16 '23 at 20:38
  • @pmacfarlane Half correct. In a situation like this, you should delete the question to prevent down votes, and then edit the question into a good question and undelete after that. – klutt Aug 17 '23 at 06:36
  • You don't need `add` or `mes` or any of that. Use `printf("Enter num%d:", i);` instead. I'll let you figure out the rest. – n. m. could be an AI Aug 18 '23 at 10:08

0 Answers0