C指针指针混淆
C pointer to a pointer confusion
我有以下代码。我试图通过使用指向指针的指针来更改 y 的值(即尝试从指向另一个指针的指针进行两次取消引用)。这是我的代码,但由于某些原因它不起作用,有人可以告诉我哪里做错了吗:
#include <stdio.h>
void changeAddr(int **j) {
(*j)++;
printf("change pointer's address to: %p\n", j);
(**j)++; // is there something wrong with this part? I want to increase the
// value pointed to by the pointer pointed to by j (so I thought
// it would be the value of y in main, but there is an error message
// the error says: *** stack smashing detected ***: terminated
printf("change the value pointed to by the pointer by using a pointer: %0d\n", **j); // this does not
// give value 7 for some reasons
}
void inval(int *i) {
(*i)++;
printf("address of i: %p\n", i);
printf("just increased: %0d \n", *i);
changeAddr(&i);
}
int main()
{
printf("Hello World\n");
int y = 5;
inval(&y);
//printf("%0d\n", y);
printf("%p\n", &y);
printf("value of y in the end: %d\n", y);
return 0;
}
int y = 5;
inval(&y);
/* inside intval(int *i): i points to a single int */
(*i)++; // Increments y
changeAddr(&i);
/* inside changeaddr(int **j): j points to a pointer to a single int */
(*j)++; // Increments i; i now points to the next thing after y;
// the spec says we can always do this but dereferencing it is undefined
(**j)++; // Increments the next thing after y; oops that's undefined behavior */
我有以下代码。我试图通过使用指向指针的指针来更改 y 的值(即尝试从指向另一个指针的指针进行两次取消引用)。这是我的代码,但由于某些原因它不起作用,有人可以告诉我哪里做错了吗:
#include <stdio.h>
void changeAddr(int **j) {
(*j)++;
printf("change pointer's address to: %p\n", j);
(**j)++; // is there something wrong with this part? I want to increase the
// value pointed to by the pointer pointed to by j (so I thought
// it would be the value of y in main, but there is an error message
// the error says: *** stack smashing detected ***: terminated
printf("change the value pointed to by the pointer by using a pointer: %0d\n", **j); // this does not
// give value 7 for some reasons
}
void inval(int *i) {
(*i)++;
printf("address of i: %p\n", i);
printf("just increased: %0d \n", *i);
changeAddr(&i);
}
int main()
{
printf("Hello World\n");
int y = 5;
inval(&y);
//printf("%0d\n", y);
printf("%p\n", &y);
printf("value of y in the end: %d\n", y);
return 0;
}
int y = 5;
inval(&y);
/* inside intval(int *i): i points to a single int */
(*i)++; // Increments y
changeAddr(&i);
/* inside changeaddr(int **j): j points to a pointer to a single int */
(*j)++; // Increments i; i now points to the next thing after y;
// the spec says we can always do this but dereferencing it is undefined
(**j)++; // Increments the next thing after y; oops that's undefined behavior */