-1

I need to populate an array of integers with an unknown number of elements. I am using a while loop to input values and exit the loop as a non integer value is entered. Outside the loop an integer j is initialized at 0 and used to address array elements inside the loop. At each round of the loop I check the value of j before and after the input value is assigned to array element v[j], then j is incremented. Depending on the size chosen for the array in the declaration, (in the example below v[8]), index j is unexpectedly affected by the assignment itself: in the example below when j equals 11 before the assignment it becomes 2 after the assignment, thereafter messing it all up. As a result the code fails to assign the correct input values to the array.

I am surely lacking some deeper knowledge about C/C++ array management... anyone can help to to fill the gap explaining the apparently strange behaviour of my code?

#include <stdio.h>
int main()
{
    int j = 0, m, v[8];
    printf("Enter an integer: to finish enter x\n");
    while (scanf("%d", &m))
    {
        printf("j before assignment:%d - ", j);
        v[j] = m;
        printf("j after assignment:%d - ", j);
        printf("v[j] after assignment:%d\n", v[j]);
        j++;
    }
    return 0;
}
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
  • If you are using c++, then use `cin`, and use a `vector` – ChrisMM Nov 25 '20 at 10:49
  • 5
    You are assigning to v[11] when the array only has a size of 8. What did you expect to happen? If you assign outside of an array bounds you get *undefined behaviour*. Undefined behaviour is often strange, and it's more or less pointless trying to understand it. Not really sure what you are expecting with this question. Please explain where your confusion is. – john Nov 25 '20 at 10:51
  • 1
    You're writing beyond the `v` array, which results in undefined behaviour which in this case may very well overwrite one or more of the other variables, because the chances are high that the compiler places all your variables next to each other. That's probably what you're seeing here. – Jabberwocky Nov 25 '20 at 11:03
  • _I am surely lacking some deeper knowledge about C/C++ array management_ : [tag:c] (as you tagged your question) **or** [tag:c++], please pick one. As stated by @ChrisMM, the proper way to achieve what you want will be very different in C++, compared to C. If you're using that language, please update your question accordingly. – PiCTo Nov 25 '20 at 11:17
  • What I need is a way to populate dynamically an array, letting it grow as I enter new values: is it a "mission impossible" task? I understand that having defined a finite size of v there are problems exceeding it, but why is the variable j affected by such problems? Isn't it an independent variable whose value gets increased at each loop turn with j++? – Mimmo49 Nov 25 '20 at 13:36
  • To fill a dynamic array, you need to allocate memory on the heap and adjust the array size as you go, see `malloc` and `free`. I changed the C++ tag to C, because the code you showed is C only. You may solve the problem more easily with C++, but then you should use `cin`, and `vector`. – Olaf Dietsche Nov 25 '20 at 13:51
  • Jabberwocky already answered the question about the independence of `v` and `j`. Search for how local variables are put on the stack or laid out in memory. See also the link I posted in my answer. – Olaf Dietsche Nov 25 '20 at 13:53
  • Thank you all for the consideration: now I will turn my attention to C++ and study how to solve my problem in both languages following your clarifications. Good to know there's people out there who can and wish to help! – Mimmo49 Nov 25 '20 at 15:36

1 Answers1

1

You write beyond the array boundaries of v. To avoid this, check j in a for loop, e.g. replace while (...) with

for (j = 0; j < 8 && scanf("%d", &m) == 1; ++j) {
    // ...
}

This way, the loop stops after the end of the array (v[7]) is reached.


To comment the "strange" behaviour, read about stack and stack layout, e.g. Does stack grow upward or downward?


As always, check the C tag wiki and the books list The Definitive C Book Guide and List

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198