我将错误的数组长度传递给了函数。为什么我没有收到错误消息?

时间:2018-09-18 04:42:21

标签: c

我是一个初学者,我正在学习c大约20天。我一直在使用YouTube。我碰到一个视频,在视频中我被告知,如果将数组传递给函数,则第二个变量应为数组的长度。我觉得不对,因此尝试了下面给出的代码。

#include <stdio.h>
#include <conio.h>

void name(int[], int);

int main() {
    int arr[] = {1,2,3};
    name(arr, 5);
    getch();
    return 0;
}

void name(int a[], int i) {
    printf("%d", i);
}

它没有给我任何错误。那么,这是正确的吗?我的意思是,第二个变量对于数组的长度真的必要吗?

2 个答案:

答案 0 :(得分:2)

我没有给我任何错误吗?不,在这种情况下,编译器不会产生任何错误,因为您只是传递了 no元素值而不是数组元素,但是如果name()函数尝试访问未绑定的元素,则会导致未定义的行为。对于例如

void name(int[], int);

int main() {
    int arr[] = {1,2,3};
    name(arr, 5);
    getch();
    return 0;
}

void name(int a[], int i) {
    printf("%d", i); /* printing variable i value is fine */
    for(int row = 0; row < i; row++) {
         printf("%d\n",a[row]);/* it cause UB when access a[3],a[4].. */

}

正确的过程是找到数组中元素的编号,将其存储到一个变量中并将该变量传递给函数,而不是某个随机数。对于例如

#include <stdio.h>
#include <stdio.h>
#include <conio.h>
void name(int[], int);
int main() {
    int arr[] = {1,2,3},ele;
    ele = sizeof(arr)/sizeof(arr[0]);
    name(arr, ele);
    getch();
    return 0;
}

void name(int a[], int ele) {
    printf("no of element in array : %d\n", ele);
    for(int row =0; row<ele; row++) {
      printf("%d\n",a[row]);
    }
}

答案 1 :(得分:2)

这里有些混乱:在C数组中,数组作为其第一个元素的指针传递给函数。结果,该函数不会自动接收有关数组元素数量的任何信息。如果需要此信息,则必须以其他方式传递它:

  • 在函数的规格中,数组大小可以固定。在这种情况下,程序员必须确保传递给该函数的数组在每个调用点具有预期的大小,以便该函数可以假定其数组参数具有正确的大小。
  • 可以从其内容推断出数组的大小:例如,C字符串是char的数组,它们以一个空字节结尾,一个char的值为零,通常写为'\0'(实际上是C中的int。指向第一个char的指针足以处理完整的字符串。
  • 数组大小可以作为额外的参数传递给函数。同样,根据功能规范,传递数组的实际大小是程序员的责任。例如,fgets()将流的内容读入char的数组中。必须传递它可以更改的最大数组元素数,该数量最多是数组大小:

    char buf[128];
    int lineno = 1;
    while (fgets(buf, sizeof buf, stdin)) {
        printf("%d\t%s", buf);
    }
    

    请注意,根据定义,数组大小可以计算为sizeof(array) / sizeof(*array)sizeof(char)1

这是修改后的示例:

#include <stdio.h>
#include <conio.h>

void output(int *a, int length) {
    int i;
    for (i = 0; i < length; i++) {
        printf("%d\n", a[i]);
    }
}

int main() {
    int arr[] = { 1, 2, 3 };
    output(arr, sizeof(arr) / sizeof(*arr));
    getch();
    return 0;
}