(C language) I'm trying to use a pointer using the parameters I got from the function, but it turned off right away without a compilation error, so I can't catch the error

Asked 2 years ago, Updated 2 years ago, 51 views

#include<stdio.h>

int leaf(int *arr,int len)
{
    int **k ;
    k = &arr;
    **(k+1)=2;// Put the secondary pointer and put the address of the arr, and it bounces
}

int main()
{
    int ab[] = {1,5,5,4,5,8,7,7};

    leaf(ab,sizeof(ab)/sizeof(int));

    for(int i=0; i<(sizeof(ab)/sizeof(int)); i++)
    {
        printf("%d",ab[i]); 
    }
}

I transferred the ab array in the main function to the leaf function The *arrr of the leaf function is because I declared it as a pointer in the function We declare k as a two-dimensional pointer and put the address of the array arr of parameters from leaf It bounces.

So I'm just going to use a one-dimensional pointer

#include<stdio.h>

int leaf(int *arr,int len)
{
    int *k ;
    k = arr; //This is a pointer, but I didn't even put the arr address value, but the value I wanted was printed out...
    *(k+1)=2;
}

int main()
{
    int ab[] = {1,5,5,4,5,8,7,7};

    leaf(ab,sizeof(ab)/sizeof(int));

    for(int i=0; i<(sizeof(ab)/sizeof(int)); i++)
    {
        printf("%d",ab[i]);

    }

But if you edit it like this,
// I'm sure int *arr is a pointer to arr, so why is that?   
}

After making the correction in this way, it worked well without any errors. On the contrary, it's even more difficult because there's no error.

c pointer array

2022-09-21 12:04

2 Answers

int leaf(int *arr,int len)
{
    int **k ;
    k = &arr;
    **(k+1)=2;// Put the secondary pointer and put the address of the arr, and it bounces
}

int main()
{
    int ab[] = {1,5,5,4,5,8,7,7};

    leaf(ab,sizeof(ab)/sizeof(int));

    for(int i=0; i<(sizeof(ab)/sizeof(int)); i++)
    {
        printf("%d",ab[i]); 
    }
}

In the code above, we handed ab to leaf as a factor, so you think ab and arr are exactly the same, right?

Well, that's not true. ab@main and arr@leaf (Let's say var@func is abbreviated from func variable in func function.) The value is clearly the same. However, the address can be different and different. So, &arr@leaf is different from &ab@main (let's say &var is a pointer to var.

If you run it in debugging mode on ideas like Visual Studio, you can see that it's different if you look at what the pointer values of the two variables are. (Or you can print out the pointer values.))


2022-09-21 12:04

I'm just curious. Why are you doing this?

Arr is a one-dimensional array (pointer), but accessing the address of the arr?

I think it's funny how it works

What do you think will happen if I approach the address of the address?

I think it's normal if there's a segment error

And is there a grammar called **k? As far as I know, it's a grammar that doesn't exist


2022-09-21 12:04

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.