简体   繁体   中英

Can an array be statically alocated if we don't know the length of the array during compilation in c99?

I'm unsure if this is correct, I included an example of what I mean:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv){
    int duzina;
    duzina = strlen(argv[1]);

    char novi[duzina+1];
    strcpy(novi, argv[1]);
    printf("%s\n", novi);

    return 0;
}

I compiled it and ran it, and it executed like intended, but I'm unsure if this is proper use of static allocation.

The novi array in your code has automatic storage duration and no linkage . It is not "statically allocated". It is a variable length array because its length has been determined at run time.

The length of an array with static storage duration is determined at compile time and cannot be changed at run time.

The only thing wrong with your code is that it does not check the number of command line arguments, so argv[1] could be a null pointer[*], and strlen(argv[1]); would then invoke undefined behavior .


[*] Technically, argv[1] could even be beyond the bounds of the argv array. Only elements up to argv[argc] exist, with argv[argc] being a null pointer. It is possible, although unlikely, that argc could be 0, although most code assumes argc > 0 .

There's no problem at all on doing that.

Actually you are not statically allocating memory (the static keyword in file scope, outside of a function, is optional but it is not in function scope, inside of a function). You are instead automatically allocating memory :

Automatic memory allocation occurs for (non-static) variables defined inside functions , and is usually stored on the stack (though the C standard doesn't mandate that a stack is used). You do not have to reserve extra memory using them, but on the other hand, have also limited control over the lifetime of this memory. Eg: automatic variables in a function are only there until the function finishes.

See also Difference between static memory allocation and dynamic memory allocation

The only limitation on your code is that you won't be able to resize the array using realloc() , but this is perfectly fine if you don't need to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM