Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

declaration - Is this a valid way to declare an array in C?

I know you're not supposed to declare arrays with a variable as the size ex. int arr[n]; because the size of an array is supposed to be static if not using dynamic memory but what about if you have a function like this? Would this be valid or no? It seems to run just fine.. Does the fact that it is declared inside a function have anything to do with it?

int main() {
  int n;
  scanf("%d", &n);
  exampleFunc(n);

}

void exampleFunc(int const n) {
  int arr[n];
  for (int i = 0; i < num; i++) {
    arr[i] = i + 1;
  }
}

Thanks for your help in advance. I'm a noob with C and every resource I've found is for other languages.

question from:https://stackoverflow.com/questions/66065600/is-this-a-valid-way-to-declare-an-array-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For starters there is a typo in the for loop

for (int i = 0; i < num; i++) {

The variable num is undeclared. It seems you mean

for (int i = 0; i < n; i++) {

The function declaration shall be placed before its call.

There is no great sense to declare the parameter with the qualifier const.

void exampleFunc(int const n);

These two function declarations

void exampleFunc(int const n);

and

void exampleFunc(int n);

declare the same one function.

This declaration of an array within the function

int arr[n];

will be valid provided that your compiler supports variable length arrays. Otherwise the compiler will issue an error that the size of the array shall be an integer constant expression.

Variable length arrays shall have automatic storage duration. So even if your compiler supports variable length arrays you may not declare them outside any function like for example

const int n = 10;
int a[n];

int main( void )
{
    //...
}

Also you may not initialize variable length arrays in their declarations.

Here is a demonstrative program of using a variable length array.

#include <stdio.h>

void display_pattern( size_t n )
{
    for ( size_t i = 0; i < n; i++ )
    {
        int a[i+1];
        
        for ( size_t j = 0; j < i + 1; j++ ) a[j] = ( i + j ) % n;
        
        for ( size_t j = 0; j < i + 1; j++ ) printf( "%d ", a[j] );
        putchar( '
' );
    }
}

int main(void) 
{
    display_pattern( 10 );
    
    return 0;
}

The program output is

0 
1 2 
2 3 4 
3 4 5 6 
4 5 6 7 8 
5 6 7 8 9 0 
6 7 8 9 0 1 2 
7 8 9 0 1 2 3 4 
8 9 0 1 2 3 4 5 6 
9 0 1 2 3 4 5 6 7 8 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...