Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

(BEGINNER) Dynamic Array Size Problem??

soda2718

New Coder
Hello I am new to coding and was just wandering why the below code:

C:
#include <stdio.h>

int main() {

for(int i = 0; 1 ; i++) {

char x;
char z[1+i];
x=getchar();
if (x == '\n'){
*(z+i) = '\0';
printf("%s",z);
break;}
*(z+i) = x;
printf("%s, %d = %c, i = %d\n",z, (z+i),*(z+i),i);
}

return 0;
}

of C does not work for inputs that are more than 15 characters? (I don't think it is beacuse of the current state of my PC since I tried it with an online compiler and it still breaks at 16 chars, but again I am new to coding.) Would appreciate any help. Thank you.
 
The code you provided has a limitation on the length of input because it declares the array z with a fixed size of 1+i. In each iteration of the loop, the code reads a character and stores it in the z array. However, the size of z increases by 1 with each iteration (1+i), resulting in a maximum size of 16 when i reaches 15.

When i becomes 15, the code tries to read the 16th character, but since z is not large enough to accommodate it, it causes undefined behavior, which may lead to program crashes, incorrect output, or other unexpected behavior.

To make the code work for inputs of any length, you can use dynamic memory allocation to create a resizable buffer. Instead of using a fixed-size array, you can allocate memory for z dynamically and expand it as needed. Here's an updated version of your code using dynamic memory allocation:

C:
#include <stdio.h>
#include <stdlib.h>

int main() {
    int size = 2; // Initial size of the buffer
    int length = 0; // Length of the string
    char* z = malloc(size * sizeof(char)); // Dynamically allocate memory
    
    for (int i = 0; ; i++) {
        char x = getchar();
        
        if (x == '\n') {
            z[length] = '\0';
            printf("%s\n", z);
            break;
        }
        
        z[length++] = x;
        
        if (length >= size) {
            size *= 2; // Double the size of the buffer
            z = realloc(z, size * sizeof(char)); // Reallocate memory
        }
    }
    
    free(z); // Free the allocated memory
    
    return 0;
}


In this updated code, the initial size of the buffer (size) is set to 2. As characters are read and stored in the z array, if the length exceeds the current size of the buffer, the code doubles the size of the buffer using realloc() to accommodate more characters. This allows the code to handle input strings of any length without limitations. Finally, the dynamically allocated memory is freed using free() before the program exits.

Note: It's important to handle memory allocation and deallocation properly to avoid memory leaks and undefined behavior. Make sure to free the allocated memory when it is no longer needed.
 
I get that malloc is the way to deal with variable size arrays, but in the original code where does the value 15 come from?

Could it be like this…

O.P. seems to hope that re-declaring the array in the loop will make it bigger. That’s not how it works.
declaring the array inside the loop creates a new array on each iteration (its scope is the block inside the for loop).
On each iteration the arrays memory is freed at the end of the block, and a new array is created at the next entry to the block.
C offers no guarantees about the contents of the newly created array, but in practice there’s a good chance that it will re-use the memory that it just freed from the previous array. That’s why this code works at least some of the time.
However, eventually the new array is too big to re-use the previous array’s memory, so it’s created somewhere else, and the previous arrays contents are now lost.
Exactly when that happens depends on the internal details of the particular compiler/os/hardware - maybe a function of the stack frame size. In this case it just happens to be at [16]

By way of confirmation, if you make each array 'more bigger' than the previous. eg z[1+I*16] then it fails after the first pass.
 
Last edited:

Buy us a coffee!

Buy me a coffee.
Back
Top Bottom