c - 为什么我只能传递数组的第一个索引?

标签 c

当我使用 getEnglishWord(counterLine); 传递数组时,counterLine 是数组。但是,当它进入 void getEnglishWord(int countLine[]) 函数时,唯一传递的是 countLine[0] 或中的第一个索引数组countLine[]

代码

if (countWords == countWordsInput + 1)
                        {
                            fclose(fpB);
                            getEnglishWord(counterLine);
                        }

void getEnglishWord(int counterLine[]) 中的代码:

int c;
        int countLine = 0, countWords = 0, countLetters = 0;
        char translatedWords[words][letters];
        int indexCount = 0;
        c = getc(fpE);

        for (int y = 0; y < words; y++)
        {
            for (int x = 0; x < letters; x++)
                translatedWords[y][x] = NULL;
        }
        while (c != EOF)
        {
            if (c == '\n')
            {
                if (countLine == counterLine[indexCount])
                {
                    translatedWords[countWords][countLetters] = c;
                    countLetters++;
                }
                indexCount++;
                countLine++;
            }

            c = getc(fpE);
        }
        fclose(fpE);
        _getch();

最佳答案

在 C 中,“T 的 N 元素数组”类型的表达式将被转换(“衰减”)为“指向 的指针”类型的表达式>T”,表达式的值将是数组第一个元素的地址。此规则的异常(exception)情况是,数组表达式是 sizeof 或一元 & 运算符的操作数,或者是用于在声明中初始化另一个数组的字符串文字。

数组对象本身不是指针;它们不存储指针值。

所以,当你打电话时

getEnglishWord(counterLine);

表达式(不是对象!)counterLine 是从类型“N 元素数组 int”转换而来>”改为“指向int的指针”,表达式的值为counterLine第一个元素的地址(&counterLine[0] )。

在函数原型(prototype)中

void getEnglishWord(int counterLine[])

声明 int counterLine[] 被视为已写入 int *counterLine; IOW,counterLine 被声明为指向 int 的指针,而不是 int 数组(这只是 true用于函数参数声明)。

因此,您的函数可以接收的只是指向数组第一个元素的指针。但是,您仍然可以在指针值上使用 [] 下标运算符(事实上,它是根据指针操作定义的,但我们不需要深入了解它)现在)。您仍然可以从函数中访问 counterLine 的所有元素,只需确保不要尝试访问超过 counterLine 末尾的元素。通常最好将数组大小作为单独的参数与数组一起传递:

void getEnglishWord ( int *counterLine, size_t counterLineSize )
{
  ...
  if ( i < counterLineSize )
    do_something_with( counterLine[i] );
  ...
}

size_t numElements = ...; // see below
getEnglishWord( counterLine, numElements );

有多种方法可以确定数组的大小。您可以对数组本身使用 sizeof 运算符,给出数组中的总字节数,并将其除以单个数组元素中的字节数:

int counterLine[N];
size_t numElements = sizeof counterLine / sizeof counterLine[0];

但这仅适用于数组表达式;您不能在指向数组第一个元素的指针上使用它。您只会得到指针的大小除以元素的大小,这不会给您您想要的结果。

否则,只需传递N:

getEnglishWord( counterLine, N );

关于c - 为什么我只能传递数组的第一个索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32723484/

相关文章:

c - 我想了解 '__attribute__((space(dma)));'的语法

C - rand() 模 0

c - arm-none-eabi-ld : section . ARM.exidx 与 .data 部分重叠

c - 使用 glTimerFunc 的 GLUT 动画

c - C 的公共(public)库是什么?

由其成员选择一个随机结构

c++ - 使用AVRstudi基于ATMega8的计算器

c - 从程序中读取 JSON 输出,然后在 C 中解析 JSON

c - C语言中如何使用管道连接两个子进程

c - 动态链接 LibCURL 时出错