我正在将C代码翻译成另一种语言。我对指针很困惑。 说我有这个代码。函数foo,调用函数bob,它们都是指针。
double
*foo(double *x, double *init, double *a){
double *y = (double*)malloc(5*sizeof(double));
double *z = (double*)malloc(5*sizeof(double));
double *sum, *update;
sum = (double*)bob(y, z) //<---Q1: why y and z don't need stars in front of them?
//I thought they are pointers?
for (i<0; i<5; i++){
z[i]=y[i] //Q2: howcome it's ok to assign y to z?
} //aren't they pointer?(i.e.hold memory address)
}
double
*bob(*arg1, *arg2){
something...
}
所以,
1)为什么y和z不需要在它们前面的星星,是不是y和z只是地址?
2)为什么sum没有星星,我认为sum被声明为指针
3)为什么可以将y分配给z?
我已经学会了这些,但他们已经太久了,有人可以给我一个提示吗?
答案 0 :(得分:0)
y=z
时,y
现在指向z
点。答案 1 :(得分:0)
答案 2 :(得分:0)
Ans for Q1:您正在将y
和z
传递给另一个函数,该函数将指针作为参数,为什么要传递指针的值?
答案2:他们是指针,你正在分配给另一个
答案 3 :(得分:0)
基本指针概念:
double a = 42.0; // a is a double
double b; // b is a double
double *x; // x is a pointer to double
x = &a; // x is the pointer, we store the address of a in pointer x
b = *x; // *x is the pointee (a double), we store the value pointed by x in b
// now b value is 42.0
答案 4 :(得分:0)
关于2)以及为什么z [i] = y [i]是可以接受的,我认为最好指向this页面,其中详细描述了数组和指针,尤其是2.1到2.8。在该特定表达式中发生的事情(不一定按顺序)是从位置y开始,获取指针,将i添加到指针,然后获取指向该位置的值。从z开始,获取指针,将i添加到指针,并将值(y [i])分配给该位置。
答案 5 :(得分:0)
double
*foo(double *x, double *init, double *a){
// x is a pointer to a double, init is a pointer to a double, a is a pointer to a double
// foo is a function returning a pointer to a double
// and taking three pointers to doubles as arguments
double *y = (double*)malloc(5*sizeof(double));
// y is a pointer to a double. It is assigned a pointer returned by malloc.
// That pointer returned by malloc points to memory space for 5 doubles.
double *z = (double*)malloc(5*sizeof(double));
// z is a pointer to a double. It is assigned a pointer returned by malloc.
// That pointer returned by malloc points to memory space for 5 doubles.
double *sum, *update;
// sum and update are pointers to doubles
sum = (double*)bob(y, z) //<---Q1: why y and z don't need stars in front of them?
//I thought they are pointers?
// sum (whose type is pointer to double)
// is assigned a pointer to double returned by bob
for (i<0; i<5; i++){
y[i] = z[i] //and are z and y pointers?!?!
// y[i] === *(y+i)
// (y + i) points to the i-th element in the space previously allocated by malloc
// *(y + i) dereferences that pointer
// equivalently, y[i] accesses the i-th element from an array
}
if(sum<0)
z=y //Q2: howcome it's ok to assign y to z?
//aren't they pointer?(i.e.hold memory address)
// after the assignment, z contains the same address as y (points to the same memory)
}
double
*bob(*arg1, *arg2){
something...
}