这个C代码为什么没有为我计算数组中元素的数量?

huangapple go评论71阅读模式
英文:

Why is this C code not counting the number of elements in the array for me?

问题

以下是代码的翻译部分:

#include <stdio.h>;

int counter(int arr[])
{
    int c = 0;
    for (int i = 0; arr[i] != '
#include <stdio.h>;

int counter(int arr[])
{
    int c = 0;
    for (int i = 0; arr[i] != '\0'; i++)
    {
        c = c + 1;
    }
    return c;
}

int main()
{
    int a[] = { 1, 5, 3 };
    int d = counter(a);
    printf("%d ", d);

    return 0;
}
'
; i++)
{ c = c + 1; } return c; } int main() { int a[] = { 1, 5, 3 }; int d = counter(a); printf("%d ", d); return 0; }

关于如何获得输出为3,你可以参考以下解释:

这段代码的目的是计算数组中的元素数量。在counter函数中,它使用一个for循环来遍历数组arr,直到遇到一个值为'\0'的元素为止。这里可能存在一个误解,因为在C语言中,数组通常不以'\0'作为结尾的标志,这通常用于表示字符串的结尾。而在这个代码中,arr是一个整数数组,不包含'\0'。

因此,为了获得正确的输出,你只需计算数组中的元素数量,而无需担心'\0'。在你的示例中,数组a有3个元素,所以counter函数将返回3,然后在main函数中将这个值打印出来,所以输出为3。

希望这能帮助你理解如何获得输出为3。

英文:

Unable to count number of elements in an array

#include &lt;stdio.h&gt;

int counter(int arr[])
{
    int c =0;
    for (int i = 0; arr[i] != &#39;
#include &lt;stdio.h&gt;
int counter(int arr[])
{
int c =0;
for (int i = 0; arr[i] != &#39;\0&#39;; i++)
{
c = c + 1;
}
return c;
}
int main()
{
int a[] = { 1, 5, 3 };
int d = counter(a);
printf(&quot;%d &quot;, d);
return 0;
}
&#39;; i++) { c = c + 1; } return c; } int main() { int a[] = { 1, 5, 3 }; int d = counter(a); printf(&quot;%d &quot;, d); return 0; }

Can anyone pls help me on how to obtain 3 as the output for this?

答案1

得分: 6

Your array needs to have a sentinel value at the end (I have chosen 0 but it can be anything which will not be considered as valid data).

#define SENTINEL 0

int counter(int arr[])
{
    int c = 0;
    for (int i = 0; arr[i] != SENTINEL; i++)
    {
        c = c + 1;
    }
    return c;
}

int main()
{
    int a[] = {1, 5, 3, SENTINEL};
    int d = counter(a);
    printf("%d\n", d);

    return 0;
}
英文:

Your array needs to have a sentinel value at the end (I have chosen 0 but it can anything which will not be considered as valid data).

#define SENTINEL 0

int counter(int arr[])
{
    int c =0;
    for (int i = 0 ; arr[i] != SENTINEL; i++)
    {
        c = c + 1;
    }
    return c;
}

int main()
{
    int a[] = {1, 5, 3, SENTINEL};
    int d = counter(a);
    printf(&quot;%d\n&quot;,d);


    return 0;
}

https://godbolt.org/z/TWGseeP8s

答案2

得分: 1

You declared an array of objects of the type int that is initialized the following way

你声明了一个`int`类型的对象数组,初始化方式如下

int a[] ={1,5,3};

So the array has three elements and neither element of the array is equal to 0.

因此,数组有三个元素,数组的任何一个元素都不等于`0`。

So this loop within the function

因此,在函数中的这个循环

for (int i=0 ; arr[i]!= '
因此,在函数中的这个循环
for (int i=0 ; arr[i]!= '\0'; i++)
'; i++)

does not make sense and results in undefined behavior.

没有意义,并导致未定义的行为。

Pay attention to that the escape character constant '\0' has the type int and may be written simply as 0. The escape character constant '\0' is usually used with character arrays (see the demonstration program below).

注意转义字符常量'
注意转义字符常量'\0'的类型是`int`,可以简单地写为`0`。转义字符常量'\0'通常与字符数组一起使用(请参见下面的演示程序)。
'的类型是`int`,可以简单地写为`0`。转义字符常量'
注意转义字符常量'\0'的类型是`int`,可以简单地写为`0`。转义字符常量'\0'通常与字符数组一起使用(请参见下面的演示程序)。
'通常与字符数组一起使用(请参见下面的演示程序)。

Moreover this function declaration

此外,这个函数声明

int counter(int arr[]);

is adjusted by the compiler to the following declaration

被编译器调整为以下声明

int counter(int *arr);

That is the parameter having array type is adjusted to pointer to the element type.

即具有数组类型的参数被调整为指向元素类型的指针。

To make your code working you need to set the last element of the array to 0 like for example

为了使您的代码工作,您需要将数组的最后一个元素设置为`0`,例如

int a[] = { 1, 5, 3, 0 };

or you could explicitly specify the number of elements equal to 4 in the array declaration like

或者您可以在数组声明中明确指定元素的数量为`4`,如下

int a[4] = { 1, 5, 3 };

In this case the last element that has no explicit initializer will be implicitly zero initialized. That is the above two declarations of the array are equivalent.

在这种情况下,没有明确初始化的最后一个元素将被隐式初始化为零。即上述两个数组的声明是等效的。

But your function actually will not return the number of elements in the array.

但是实际上,您的函数不会返回数组中的元素数量。

It returns the number of elements in the array before the element with the value equal to 0 provided that such an element indeed exists in the array. However, an array can be declared with more elements than the number of elements with the value 0.

它返回数组中在具有值等于`0`的元素之前的元素数量,前提是数组中确实存在这样的元素。然而,数组可以声明具有比值为`0`的元素数量更多的元素。

So in general your approach is wrong.

因此,一般而言,您的方法是错误的。

The for loop used in your function is usually used to determine the length of a string stored in a character array because strings are sequences of characters terminated by the zero character '\0'.

您函数中使用的for循环通常用于确定存储在字符数组中的字符串的长度,因为字符串是由零字符'
您函数中使用的for循环通常用于确定存储在字符数组中的字符串的长度,因为字符串是由零字符'\0'终止的字符序列。
'终止的字符序列。

Here is a demonstration program

这是一个演示程序

#include <stdio.h>

size_t counter( const char s[] )
{
    size_t n = 0;

    for ( size_t i = 0 ; s[i] != '
这是一个演示程序
#include <stdio.h>
size_t counter( const char s[] )
{
size_t n = 0;
for ( size_t i = 0 ; s[i] != '\0'; i++ )
{
++n;
}
return n;
}
int main( void )
{
char s[] = "Hello World!";
size_t n = counter( s );
printf( "The length of the string is %zu\n", n );
return 0;
}
'; i++ ) { ++n; } return n; } int main( void ) { char s[] = "Hello World!"; size_t n = counter( s ); printf( "The length of the string is %zu\n", n ); return 0; }

But integer arrays can have an element with the value 0 as an actual element of the arrays.

但是整数数组可以有一个值为0的元素作为实际的数组元素。

So your approach will not work.

因此,您的方法不会起作用。

To determine the number of elements of the array you could just write

要确定数组的元素数量,您可以简单地写成

#include <stdio.h>

int main( void )
{
    int a[] = { 1,5,3 };

    size_t n = sizeof( a ) / sizeof( *a );

    printf( "%zu\n", n );

    return 0;
}
英文:

You declared an array of objects of the type int that is initialized the following way

int a[] ={1,5,3};

So the array has three elements and neither element of the array is equal to 0.

So this loop within the function

for (int i=0 ; arr[i]!= &#39;
for (int i=0 ; arr[i]!= &#39;\0&#39;; i++)
&#39;; i++)

does not make sense and results in undefined behavior.

Pay attention to that the escape character constant &#39;\0&#39; has the type int and may be written simply as 0. The escape character constant &#39;\0&#39; is usually used with character arrays (see the demonstration program below).

Moreover this function declaration

int counter(int arr[]);

is adjusted by the compiler to the following declaration

int counter(int *arr);

That is the parameter having array type is adjusted to pointer to the element type.

To make your code working you need to set the last element of the array to 0 like for example

int a[] = { 1, 5, 3, 0 };

or you could explicitly specify the number of elements equal to 4 in the array declaration like

int a[4] = { 1, 5, 3 };

In this case the last element that has no explicit initializer will be implicitly zero initialized. That is the above two declarations of the array are equivalent.

But your function actually will not return the number of elements in the array.

It returns the number of elements in the array before the element with the value equal to 0 provided that such an element indeed exists in the array. However an array can be declared with more elements then the number of the element with the value 0.

So in general your approach is wrong.

The for loop used in your function is usually used to determine the length of a string stored in a character array because strings are sequence of characters terminated by the zero character &#39;\0&#39;.

Here is a demonstration program

#include &lt;stdio.h&gt;

size_t counter( const char s[] )
{
    size_t n = 0;

    for ( size_t i = 0 ; s[i] != &#39;
#include &lt;stdio.h&gt;
size_t counter( const char s[] )
{
size_t n = 0;
for ( size_t i = 0 ; s[i] != &#39;\0&#39;; i++ )
{
++n;
}
return n;
}
int main( void )
{
char s[] = &quot;Hello World!&quot;;
size_t n = counter( s );
printf( &quot;The length of the string is %zu\n&quot;, n );
return 0;
}
&#39;; i++ ) { ++n; } return n; } int main( void ) { char s[] = &quot;Hello World!&quot;; size_t n = counter( s ); printf( &quot;The length of the string is %zu\n&quot;, n ); return 0; }

But integer arrays can have an element with the value 0 as an actual element of the arrays.

So your approach will not work.

To determine the number of elements of the array you could just write

#include &lt;stdio.h&gt;

nt main( void )
{
    int a[] = { 1,5,3 };

    size-t n = sizeof( a ) / sizeof( *a );

    printf( &quot;%zu\n&quot;, n );

    return 0;
}

答案3

得分: 1

你尝试检查数组的最后一个值是否为\0,尽管它从未被声明。

在C中找到数组长度的常见方式是使用ARRAY_LENGTH宏:

#include <stdio.h>
#define ARRAY_LENGTH(x) (sizeof(x) / sizeof((x)[0]))

int main()
{
    int a[] = {1, 5, 3};
    printf("%zu\n", ARRAY_LENGTH(a));
    return 0;
}

顺便说一下,这一切都在编译时完成,因为sizeof在编译时已知,所以效率更高 这个C代码为什么没有为我计算数组中元素的数量?

编译程序后,你将看到类似以下的输出(当然是伪代码):

int main()
{
    int a[] = {1, 5, 3};
    printf("%zu\n", 3);
    return 0;
}
英文:

You try and check for the \0 value as the last value of the array although it was never declared.

The common way of finding the array length in C is to use the ARRAY_LENGTH macro:

#include &lt;stdio.h&gt;
#define ARRAY_LENGTH(x) (sizeof(x) / sizeof((x)[0]))

int main()
{
    int a[] = {1, 5, 3};
    printf(&quot;%zu\n&quot;,ARRAY_LENGTH(a));
    return 0;
}

By the way, this is all done in compilation since sizeof is known in compilation time, so it's even more efficient 这个C代码为什么没有为我计算数组中元素的数量?

After compiling the program, you will see something like this (pseudo of course):

int main()
{
    int a[] = {1, 5, 3};
    printf(&quot;%zu\n&quot;, 3);
    return 0;
}

huangapple
  • 本文由 发表于 2023年3月15日 20:48:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75744931.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定