代码之家  ›  专栏  ›  技术社区  ›  Nick S Arnold

限制数组大小的目的是什么?

  •  8
  • Nick S Arnold  · 技术社区  · 6 年前

    restrict

    #include <stdio.h>
    
    char* foo(char s[restrict], int n)
    {
            printf("%s %d\n", s, n);
            return NULL;
    }
    
    int main(void)
    {
            char *str = "hello foo";
            foo(str, 1);
    
            return 0;
    }
    

    已成功编译 gcc main.c -Wall -Wextra -Werror -pedantic

    在这种情况下,restrict如何工作并由编译器进行解释?

    2 回复  |  直到 6 年前
        1
  •  8
  •   Sourav Ghosh    6 年前

    首先,

      char* foo(char s[restrict], int n) { ....
    

    与相同

      char* foo(char * restrict s, int n) {...
    

    C11 ,章§6.7.6.2

    […]可选类型限定符和关键字 static 使用数组类型声明函数参数,然后仅在最外层 数组类型派生。

    restricted 这里提示编译器,对于函数的每个调用,实际参数是 只有 通过指针访问 s .

        2
  •  4
  •   Mike Kinghan Luchian Grigore    6 年前

    restrict type qualifier

    在函数声明中,关键字restrict可能出现在用于声明函数参数的数组类型的方括号内。它限定数组类型转换到的指针类型:

    例如:

    void f(int m, int n, float a[restrict m][n], float b[restrict m][n]);