C-计数数组长度的方法

发布于 2025-02-12 17:24:56 字数 555 浏览 1 评论 0原文

我需要阵列的长度。一种方法可以很好地工作,一个方法给出了错误的答案,并且没有编译。

这不会编译:

size_t len = sizeof(array) / sizeof(array[0]);    

这仅计算前4个字母:

size_t len = sizeof(array) / sizeof(char);

len = 12工作。

我真的不明白这一点,因此非常感谢一些提示。

const char array[] = {'t', 'h', 'i', 's', 'i', 's', 'm', 'y', 't', 'e', 'x', 't', '\0'};

void count_chars(const char *array, unsigned int *counts)
{
    size_t len = 12;
    
    for(size_t i = 0; i < len; i++){
        counts[(int)array[i]]++;
    }
}

I need the length of an array. One way works perfectly, one gives the wrong answer, and one doesn't compile.

This doesn't compile:

size_t len = sizeof(array) / sizeof(array[0]);    

This counts only first 4 letters:

size_t len = sizeof(array) / sizeof(char);

And len = 12 works.

I really don't understand this so some hint is greatly appreciated.

const char array[] = {'t', 'h', 'i', 's', 'i', 's', 'm', 'y', 't', 'e', 'x', 't', '\0'};

void count_chars(const char *array, unsigned int *counts)
{
    size_t len = 12;
    
    for(size_t i = 0; i < len; i++){
        counts[(int)array[i]]++;
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

自由范儿 2025-02-19 17:24:57

您无法确定传递的数组内部功能的大小。您需要将大小作为附加参数传递。

const char array[] = {'t', 'h', 'i', 's', 'i', 's', 'm', 'y', 't', 'e', 'x', 't', 0};

void count_chars(const char *arr, unsigned int *counts, size_t size)
{
    for(size_t i = 0; i < size; i++)
        counts[(unsigned)arr[i]]++;
}

int main(void)
{
    int cnt[sizeof(array[0]) * (1 << CHAR_BIT)];

    count_chars(array, cnt, sizeof(array) / sizeof(array[0]));
}

您需要施放到无符号(不是int),因为char> char值可能为负。

You cant determine the size of the passed array inside function. You need to pass size as an additional parameter.

const char array[] = {'t', 'h', 'i', 's', 'i', 's', 'm', 'y', 't', 'e', 'x', 't', 0};

void count_chars(const char *arr, unsigned int *counts, size_t size)
{
    for(size_t i = 0; i < size; i++)
        counts[(unsigned)arr[i]]++;
}

int main(void)
{
    int cnt[sizeof(array[0]) * (1 << CHAR_BIT)];

    count_chars(array, cnt, sizeof(array) / sizeof(array[0]));
}

You need to cast to unsigned (not int) because char values can be negative.

全部不再 2025-02-19 17:24:57

实际上,您要做的是在C中不可能做的。一般的经验法则是计算声明数组的功能中数组的长度并将其传递给函数。这是由于以下事实:C调用函数时不会传递整个数组,而只是将基本地址作为指针变量。分解您的方法和他们不工作的原因是:

size_t len = sizeof(array) / sizeof(array [0]); < / p>

这是普遍接受的方法,但先决条件是必须在同一范围内声明数组,而不是指针。

size_t len = sizeof(array) / sizeof(char); < / p>

由于数组是指针一个类型变量,因此具有尺寸4(在32位计算机上至少)用大小(char)(char)的尺寸为1,结果为1

size_t len = 12;

这是用硬编码而起作用的。

在您的情况下,可以使用一个简单的解决方案:

size_t len = strlen(array)

如前所述,假设您可以保证最后一个元素为0或'\ 0'。在这种情况下,您也可以简单地将循环条件修改为:

for(int i = 0; array[i] != 0; i++) {
    ...
}

希望我可以澄清您的疑问

What you are trying to do is actually impossible in C. The general rule of thumb is to calculate the length of the array in the function where the array is declared and pass it to the function. This is due to the fact that C doesn't pass the entire array when calling a function but rather just the base address as a pointer variable. To breakdown your approaches and the reason they do/don't work are:

size_t len = sizeof(array) / sizeof(array[0]);

This the commonly accepted approach but the prerequisite is that array must be declared in the same scope not be a pointer.

size_t len = sizeof(array) / sizeof(char);

As array is pointer a type variable and therefore has the size 4(atleast on 32-bit machines) dividing by sizeof(char) is 1 resulting in the answer 4

size_t len = 12;

This works as it's hard coded.

An easy solution in your case could be use:

size_t len = strlen(array)

as mentioned assuming you can guarantee that the last element will be 0 or '\0'. In this situation you could also simply modify the looping condition to:

for(int i = 0; array[i] != 0; i++) {
    ...
}

Hope I could clarify your doubt

娇俏 2025-02-19 17:24:57

size_t len = sizeof(array) / sizeof(array [0]); < / p>

这是获取数组长度的一般方法。但是,这将在count_chars函数中无法使用,因为数组被定义为API内部的本地变量(指针)。如果是这种情况,结果将为13(不是您提到的12个),因为它在末尾还计算\ 0。

对于字符串,可以使用strlen。与问题一样,您期望结果= 12,因此这可能是您正确的解决方案。但是,如果中间有一些\ 0值,这将无法工作,因为它会找到第一个String terminator(\ 0)。

size_t len = sizeof(array) / sizeof(array[0]);

This is general approach for getting the length of an array. However, this will not work inside count_chars function because array is defined as local variable (a pointer) inside the API. And if it is the case, the result will be 13 (not 12 as you mentioned) because it count also the \0 at the end.

For string of characters, it is possible to use strlen. As in the question, you expected result = 12 so this might be your right solution. However, this will not work if there is some \0 value in the middle because it will find first string terminator (\0).

橘虞初梦 2025-02-19 17:24:57

c 中,如果要获得 null终止字符串的长度,则必须检查null \ 0 和计数字符。

在这里检查Strlen方法的工作原理。

//Custom Strlen function.
size_t my_strlen(const char *str)
{
    register const char *s;

    for (s = str; *s; ++s);
    return(s - str);
}

”阵列的长度(一般)等int,float,double您可以在下面使用。

size_t int_arr_len = sizeof(int_arr) / sizeof(int_arr[0]);
size_t float_arr_len = sizeof(float_arr) / sizeof(float_arr[0]);

下面的完整源代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char char_arr[] = {'t', 'h', 'i', 's', 'i', 's', 'm', 'y', 't', 'e', 'x', 't', 0}; // `\0` Null Terminated.
const int int_arr[] = {10, 20, 30, 40, 50};
const float float_arr[] = {1.5f, 2.5f, 3.5f, 4.5f, 5.5f};

//Custom Strlen function.
size_t my_strlen(const char *str)
{
    register const char *s;

    for (s = str; *s; ++s);
    return(s - str);
}

int main()
{

    //Array length for Strings(Char array. Null Terminated. `\0`)
    size_t char_arr_len1 = strlen(char_arr);
    size_t char_arr_len2 = my_strlen(char_arr);

    //Array length for General arrays like Int,Float,Double...etc
    size_t int_arr_len = sizeof(int_arr) / sizeof(int_arr[0]);
    size_t float_arr_len = sizeof(float_arr) / sizeof(float_arr[0]);

    //Print length of arrays.
    printf("char_arr_len1: %zu\n", char_arr_len1);
    printf("char_arr_len2: %zu\n", char_arr_len2);
    printf("int_arr_len: %zu\n", int_arr_len);
    printf("float_arr_len: %zu\n", float_arr_len);

    return 0;
}

In C if you want to get length of Null Terminated Strings you have to check for NULL \0 and count characters.

Check here how strlen method works.

//Custom Strlen function.
size_t my_strlen(const char *str)
{
    register const char *s;

    for (s = str; *s; ++s);
    return(s - str);
}

Strlen Source

To count length of Arrays (General) like Int,Float,Double you can use below method.

size_t int_arr_len = sizeof(int_arr) / sizeof(int_arr[0]);
size_t float_arr_len = sizeof(float_arr) / sizeof(float_arr[0]);

Full Source Code below

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char char_arr[] = {'t', 'h', 'i', 's', 'i', 's', 'm', 'y', 't', 'e', 'x', 't', 0}; // `\0` Null Terminated.
const int int_arr[] = {10, 20, 30, 40, 50};
const float float_arr[] = {1.5f, 2.5f, 3.5f, 4.5f, 5.5f};

//Custom Strlen function.
size_t my_strlen(const char *str)
{
    register const char *s;

    for (s = str; *s; ++s);
    return(s - str);
}

int main()
{

    //Array length for Strings(Char array. Null Terminated. `\0`)
    size_t char_arr_len1 = strlen(char_arr);
    size_t char_arr_len2 = my_strlen(char_arr);

    //Array length for General arrays like Int,Float,Double...etc
    size_t int_arr_len = sizeof(int_arr) / sizeof(int_arr[0]);
    size_t float_arr_len = sizeof(float_arr) / sizeof(float_arr[0]);

    //Print length of arrays.
    printf("char_arr_len1: %zu\n", char_arr_len1);
    printf("char_arr_len2: %zu\n", char_arr_len2);
    printf("int_arr_len: %zu\n", int_arr_len);
    printf("float_arr_len: %zu\n", float_arr_len);

    return 0;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文