获取输入并使用它来初始化数组有效,但根据 C ,它不应该
Getting input and using it to initialize array works, but according to C , it shouldn't
代码从字面上从用户那里获取输入并分配数组,并且它在在线 gdb 和 geeksforgeeks 问题提交中有效? !?!?!?
int n;
int [n];
这行得通!无论我在哪里搜索,数组中的 n 应该是一个常量。
这是问题的 link 和我朋友写的代码。
代码
#include <stdio.h>
int main()
{
int t,n;
int rear;
int front;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
int a[n],s[n];
int temp;
for(int i=0;i<n;i++)
a[i]=i+1;
front=0;
rear=n-1;
//rotation
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
temp=a[front];
if(front == rear)
{
front = -1;
rear = -1;
}
else
{
front = (front+1) % n;
}
//dequeue
if(front == -1)
{
front = 0;
}
rear = (rear + 1) % n;
a[rear] = temp;
//enqueue
}
temp=a[front];
if(front == rear)
{
front = -1;
rear = -1;
}
else
{
front = (front+1) % n;
}
s[temp-1]=i;
//dequeue
}
for(int i=0;i<n;i++)
printf("%d\t",s[i]);
printf("\n");
}
return 0;
}
这是一个 VLA,它是在 C99
中添加的,但从 C11
开始,它是一个可选功能。
引用标准:
If the size is not present, the array type is an incomplete type. If the size is *
instead of being an expression, the array type is a variable length array type of unspecified size, which can only be used in declarations or type names with function prototype scope; such arrays are nonetheless complete types. If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; otherwise, the array type is a variable length array type. (Variable length arrays are a conditional feature that implementations need not support; see 6.10.8.3.)
代码从字面上从用户那里获取输入并分配数组,并且它在在线 gdb 和 geeksforgeeks 问题提交中有效? !?!?!?
int n;
int [n];
这行得通!无论我在哪里搜索,数组中的 n 应该是一个常量。
这是问题的 link 和我朋友写的代码。
代码
#include <stdio.h>
int main()
{
int t,n;
int rear;
int front;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
int a[n],s[n];
int temp;
for(int i=0;i<n;i++)
a[i]=i+1;
front=0;
rear=n-1;
//rotation
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
temp=a[front];
if(front == rear)
{
front = -1;
rear = -1;
}
else
{
front = (front+1) % n;
}
//dequeue
if(front == -1)
{
front = 0;
}
rear = (rear + 1) % n;
a[rear] = temp;
//enqueue
}
temp=a[front];
if(front == rear)
{
front = -1;
rear = -1;
}
else
{
front = (front+1) % n;
}
s[temp-1]=i;
//dequeue
}
for(int i=0;i<n;i++)
printf("%d\t",s[i]);
printf("\n");
}
return 0;
}
这是一个 VLA,它是在 C99
中添加的,但从 C11
开始,它是一个可选功能。
引用标准:
If the size is not present, the array type is an incomplete type. If the size is
*
instead of being an expression, the array type is a variable length array type of unspecified size, which can only be used in declarations or type names with function prototype scope; such arrays are nonetheless complete types. If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; otherwise, the array type is a variable length array type. (Variable length arrays are a conditional feature that implementations need not support; see 6.10.8.3.)