这是为什么数组大小"解决方法:QUOT;给我一个警告? [英] Why is this array size "workaround" giving me a warning?

查看:191
本文介绍了这是为什么数组大小"解决方法:QUOT;给我一个警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,数组衰变时为在C参数传递但是数组的数组只衰减到阵列的指针的指针;因此,如果我们附上我们原来的数组本身在数组中,我们可以封闭阵列突入功能后找回原来的数组的长度。下面是测试这个想法的程序:

As is well known, arrays decay to pointers when passed as parameters in C. But an array of arrays only decays to a pointer of arrays; hence if we enclose our original array itself in an array, we can retrieve the original array length after passing the enclosing array into a function. Here's a program that tests this idea:

/* array_workaround.c */

#include <stdio.h>

void printsize(char array_pointer[][10]);

int main(void)
{
    char a[10];

    for(char i = 0; i < 10; i++)
        a[i] = i;

    char a_p[1][10] = {a};

    printsize(a_p);

    return 0;
}

void printsize(char array_pointer[][10])
{
    printf("%lu\n", sizeof(array_pointer[0]));
}

在运行,它打印出正确的值( 10 ),但是编译器给出了这样的警告:

When run, it prints out the correct value (10), but the compiler gives this warning:

array_workaround.c:12:24: warning: incompatible pointer to integer conversion
      initializing 'char' with an expression of type 'char [10]' [-Wint-conversion]
    char a_p[1][10] = {a};

当然,这个变通方法的问题在于,它需要的数组的大小是硬codeD插入函数接受它,这类型的失败的全部目的。然而,这并不意味着该数组检查是正确的大小,而不需要在长度作为一个单独的参数来传递......(只要它总是10!笑)。

Of course, the issue with this "workaround" is that it requires that the size of the array be hard-coded into the function receiving it, which sort of defeats the whole purpose. However, it does mean that the array is checked to be of the right size, without having to pass in the length as a separate parameter... (as long as it's always 10! lol).

所以,这是怎么回事的警告?是编译器根本就没有足够聪明,知道是怎么回事就不会损坏任何数据?还是我刚开幸运不知何故?任何人都可以看到一个方法,使一个的实际的解决办法,这样你就不必在那里硬code中的10号?

So what is going on with the warning? Is the compiler simply not "smart enough" to know that what is going on here doesn't corrupt any data? Or am I just getting lucky somehow? Can anyone see a way to make it an actual workaround so that you don't have to hard-code the number 10 in there?

推荐答案

char a_p[1][10] = {a};

A ,这是基址 A 并具有指针的类型<$ c的值$ C>字符,用于初始化 a_p [0] [0] ,这应该是一个字符,这就是为什么编译器为您提供了转换警告。

the value of a, which is the base address of a and has type of pointer to char, is used to initialize a_p[0][0], which should be a char, that is why compiler gives you that conversion warning.

这篇关于这是为什么数组大小&QUOT;解决方法:QUOT;给我一个警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆