What is size_t in C?

前端 未结 13 1700
礼貌的吻别
礼貌的吻别 2020-11-22 05:00

I am getting confused with size_t in C. I know that it is returned by the sizeof operator. But what exactly is it? Is it a data type?

Let\'

13条回答
  •  有刺的猬
    2020-11-22 05:23

    size_t or any unsigned type might be seen used as loop variable as loop variables are typically greater than or equal to 0.

    When we use a size_t object, we have to make sure that in all the contexts it is used, including arithmetic, we want only non-negative values. For instance, following program would definitely give the unexpected result:

    // C program to demonstrate that size_t or
    // any unsigned int type should be used 
    // carefully when used in a loop
    
    #include
    int main()
    {
    const size_t N = 10;
    int a[N];
    
    // This is fine
    for (size_t n = 0; n < N; ++n)
    a[n] = n;
    
    // But reverse cycles are tricky for unsigned 
    // types as can lead to infinite loop
    for (size_t n = N-1; n >= 0; --n)
    printf("%d ", a[n]);
    }
    
    Output
    Infinite loop and then segmentation fault
    

提交回复
热议问题