c++ - sizeof - 将指针转换为数组

标签 c++ c

<分区>

Possible Duplicate:
How to find the sizeof(a pointer pointing to an array)

我有以下代码

int myfunc(char *arr)
{
const int sizearr = sizeof( arr ) / sizeof(char);
}

这会产生指针的大小,而不是我传递给函数的 char 数组 [17] 的大小。

我知道我可以使用 strlen 来解决问题,但是有什么方法可以将 char*arr 指针转换回我传递给函数的 char 数组 [17] 以便使用 sizeof(char array[ 17]) ?

最佳答案

如果要传递 17 个字符的数组,则需要通过引用传递它(仅限 C++):

int myfunc(char (&arr)[17])
{
    unsigned int const sizearr = sizeof arr;
    // ...
}

或者做一个模板来推断大小:

template <unsigned int sizearr>
int myfunc(char (&arr)[sizearr])
{
    // ...
}

在 C 中,您根本无法将数组作为参数传递,因此有责任单独传达数组大小。

更新:正如@David 建议的那样,您可以通过传递指向数组的指针来修复 C 中的数组类型:

int myfunc(char (*arr)[17])
{
    unsigned int const sizearr = sizeof *arr;
    // ...
}

int main()
{
    char s[17];
    return myfunc(&s);
}

关于c++ - sizeof - 将指针转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12530498/

相关文章:

c++ - 构造函数 : Why does 'explicit' prevent assignment construction?

c++ - 在不更改代码的情况下使用 .in 文件进行测试

c++ - shared_ptr.get() 可以被多个线程调用,而另一个线程锁定并调用 shared_ptr.swap() 吗?

c++ - 更改单个 QTabWidget 选项卡的颜色

c - Scanf 不会扫描结构内部数据

c - 地址作为 sizeof() 运算符中的操作数

c - 这个代码是不是不正确?

c++ - 比较两个 std::list 列表并得到不同的对象

c - 如何打开文件并将其锁定在C中?

c - 4 位 4x20 LCD,采用 Atmega32