Initializing a different array in each iteration of a loop in C

I was trying to do a question in which I was to ask for input from the user and store that input in an array many times (so I used a loop). However, even though I declared and initialized a new char array in each iteration and store in a char * array, all char array(I was trying to use them as strings in this case) stored in the char * array seem to have the same memory address, even if I declare a new one each time! How is this happening?

Great thanks!!

Below is a simplified snippet of codes to demonstrate the behaviour I am talking about. When it is run, all outputs were just 9. The 'ask for input' is simplified to inserting index-related values in the array

int main(int argc, char** argv){

    char* batsman[10];
    for(int i = 0; i < 10; i++){
        char newString[2];
        newString[0] = i + 48;
        newString[1] = '\0';
        batsman[i] = newString;

    for(int i = 0; i < 10; i++){
    return 0;

3 Answers Initializing a different array in each iteration of a loop in C

The compiler is free to choose where to allocate space for the array. Since newString is local to the loop, it's most efficient to just keep it in the same location. Keep in mind, it's not guaranteed to always be the case.

6 days ago

There is no reason to think that wouldn't happen.

You create an object (an array), then it goes out of scope (when the loop ends). Now its place in memory is free for something else to take.

As it happens (pure chance) your next object (another array) got the same address. Next time it might be different. It doesn't matter!

When you move house, do you care who moves into it afterwards? Maybe it lays empty for a few years. Maybe it lays empty until it's demolished to make room for a row of shops. Maybe it's taken up straight away by a lovely family who repaint it and turn it into a laughter palace. But you're not there any more so it couldn't make the slightest difference to you either way. You've gone. You've moved house.

Never mind that. Your program is broken because you are storing dangling pointers to variables that go out of scope. Don't do that. Use std::vector<std::string> instead.

Consult your book for further information on the complexities of "raw" C-style arrays.

6 days ago

The problem comes because you are not using memory allocation. You are storing in batsman pointers to characters defined inside the loop. The compiler uses the same memory location in every loop (this is the case here, can change) so when you modify the value inside the loop, you are doing that for every number as every pointer are pointing the same memory location.

To solve this you need to use dynamic memory allocation with malloc and free from the c standard library.

6 days ago