简体   繁体   English

当 arrays 通过函数作为 arguments 传递时,它们是否被零索引? C编程

[英]Are arrays zero indexed when they are passed throu functions as arguments? C programming

Are array zero indexed when they are passed throu an function as argument?当它们通过 function 作为参数传递时,数组零索引了吗? Or did C just copy the array A's memory into two different arrays?还是 C 只是将数组 A 的 memory 复制到两个不同的 arrays 中?

I never need to "reset" the orginal position of an array when I pass the same array throu another function?当我通过另一个 function 传递同一个数组时,我永远不需要“重置”一个数组的原始 position?

static const int A[3] = {1, 5, 8};

void fun(const int B[]){
    printf("val = %d\n", *B);
    B++;
    printf("val = %d\n", *B);
}

int main() {

    fun(A);
    fun(A);

    return 0;
}

Output: Output:

val = 1
val = 5
val = 1
val = 5

For example when I don't use const , I can see that they share the same memory, but that'only when I don't use const .例如,当我不使用const时,我可以看到它们共享相同的 memory,但那只是在我不使用const时。

static int A[3] = {1, 5, 8};

void fun(int B[]){
    printf("val = %d\n", *B);
    *B = 10;
    printf("val = %d\n", *B);
}

int main() {

    fun(A);
    fun(A);

    return 0;
}

Output: Output:

val = 1
val = 10
val = 10
val = 10

You modify local pointer.您修改本地指针。 Why pointer?为什么是指针? Because array are passed as pointers.因为数组作为指针传递。 To modify the original pointer you need to pass pointer to pointer要修改原始指针,您需要将指针传递给指针

int A[] = {1, 5, 8, 10};

void fun(const int **B){
    printf("val = %d\n", **B);
    (*B)++;
    printf("val = %d\n", **B);
}

int main() 
{
    int *C = A;
    fun(&C);
    fun(&C);

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM