修改阵列C中的函数 [英] Modifying a array in a function in C

查看:79
本文介绍了修改阵列C中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

void array_tester(int *array);

int main(int argc,char *argv[])
{   
    int test[] = {1,1,1,1};
    int print;
    for(print = 0; print < sizeof(test) / sizeof(int); print++)
    {
        printf("%d\n",test[print] );
    }

    array_tester(test);
    for(print = 0;print < sizeof(test)/sizeof(int);print++)
    {
        printf("%d\n",test[print] );
    }

    return EXIT_SUCCESS;
}


void array_tester(int array[])
{   
    int i ;
    for(i = 0; i < sizeof(array) / sizeof(int); i++)
    {
        array[i] = i;
    } 
}

问题是我想修改 array_tester 函数的数组,但我不能这样做。我怎么在使用的sizeof()

The problem is I want to modify the the array in the array_tester function but I'm unable to do so. What do I use inside sizeof()?

推荐答案

您必须手动传递有关数组大小的信息。

You have to manually pass the information about the size of the array.

void array_tester( int* array , int size ) ;

然后调用它:

array_tester( test , sizeof(test)/sizeof(*test) ) ;

这背后的原因是,数组传递给函数会衰减到一个指针和的sizeof 将返回指针的大小不是原来的数组。

The reason behind this is that array passed to a function will decay to a pointer and the sizeof will return the size of pointer not the original array.

这篇关于修改阵列C中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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