如何知道传递给函数的 char 数组的大小(以字节为单位)? [英] How to know the size (in bytes) of a char array passed to a function?

查看:39
本文介绍了如何知道传递给函数的 char 数组的大小(以字节为单位)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试 sizeof 运算符.在我的代码中的两种情况下,我得到了 指针的大小(我认为).在其他情况下,我得到数组占用多少字节.当我将数组传递给函数时,如何获取以字节为单位的数组大小?sizeof 运算符还不够吗?我做错了吗?

I am testing the sizeof operator. In two cases in my code, I get the size of the pointer (I think). In the other cases I get how many bytes the arrays occupy. How can I get the size of the array in bytes when I pass it to a function? Isn't the sizeof operator enough? Am I doing something wrong?

#include <stdio.h>

/*Testing the operator sizeof*/

void test (char arrayT[]);
void test2 (char *arrayU);

int main(int argc, char *argv[]){

    char array1[7];
    printf("array1 size is:%d
", sizeof array1);
    /*array1 size is: 7*/

    char array2[] = { '1', '2', '3', '4', '5', '6', '7'};
    printf("array2 size is:%d
", sizeof array2);
    /*array2 size is: 7*/

    char array3[] = "123456";
    printf("array3 size is:%d
", sizeof array3);
    /*array3 size is: 7*/

    unsigned char array4[] = "123456";
    printf("array4 size is:%d
", sizeof array4);
    /*array4 size is: 7*/

    char arrayX[] = "123456";
    test(arrayX);
    /*arrayT size is: 4*/

    char arrayY[] = "123456";
    test2(&arrayY[0]);
    /*arrayU size is: 4*/

    return 0;
}

void test (char arrayT[]){
    printf("arrayT size is:%d
", sizeof arrayT);
}

void test2 (char *arrayU){
    printf("arrayU size is:%d
", sizeof arrayU);
}

推荐答案

将数组传递给函数时,实际发生的是传递了指向数组中第一个元素的指针.换句话说,数组衰减为指向第一个元素的指针.

When an array is passed to a function, what's actually happening is that a pointer to the first element in the array is being passed. Put another way, the array decays into a pointer to the first element.

在这两个声明中:

void test (char arrayT[]);
void test2 (char *arrayU);

arrayTarrayU 由于这种衰减而具有完全相同的类型,并且 sizeof 将为两者返回相同的值,即char * 的大小.

arrayT and arrayU are of exactly the same type due to this decay, and sizeof will return the same value for both, i.e. the size of a char *.

对比一下:

char array1[] = "a string";
char *array2;

其中 array1 实际上是一个大小为 9 的数组,而 array2 是一个大小(在您的系统上)为 4 的指针.

Where array1 is actually an array of size 9, while array2 is a pointer whose size (on your system) is 4.

因此,无法知道传递给函数的数组的长度.您需要将大小作为单独的参数传入:

Because of this, there is no way to know the length of an array passed to a function. You need to pass in the size as a separate parameter:

void test (char arrayT[], size_t len);

这篇关于如何知道传递给函数的 char 数组的大小(以字节为单位)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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