【发布时间】:2018-04-19 19:38:56
【问题描述】:
我正在通过 CPP 学院 CLA 课程材料进行第二次阅读,但我仍在为指针而苦苦挣扎。这是我试图理解的代码 sn-p。我在下面的代码中评论了我的逻辑。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
// we are dereferencing pointer t of type float
// to = integer literal 1 + float pointer to memory location size
// of 2xfloats.
// I am guessing that this memory location will be filled with
// all zeroes or this assignment is invalid.
// This initial assignment is completely confusing me
// and rest of my logic/reading this snippet is probably wrong :D
float *t = 1 + (float *) malloc(sizeof(float) * sizeof(float));
printf("%f\n",*t); //0.00000
t--; //we move pointer to next zero in memory?!
printf("%f\n",*t); //0.00000
*t = 8.0; //we dereference pointer t and assign literal
//8.0. This will be [0] position
printf("%f\n",*t); //8.00000
t[1] = *t / 4.0; //we assign index position [1] to (*t (which
//is previously assigned to 8.0) divided by
//4.0 . This will assign t[1] to 2)
printf("%f\n",*t); //2.00000
t++; //we move pointer to next position [1] = 2
printf("%f\n",*t); //2.00000
t[-1] = *t / 2.0; //moving to position [0] and assigning it to 1
printf("%f\n",*t); //2.00000
free(--t);
return 0;
}
抱歉,我没有提到这不是工作计划的一部分。这是一长串简短的“技巧”sn-ps,用于检查对材料的理解。我将仔细阅读您提供的详细答案。谢谢大家:D
【问题讨论】:
-
这里有什么问题?
-
您的代码注释“我猜这个内存位置将被全零填充”不正确 - 不要猜,阅读
malloc手册页! -
请记住,指针算法会考虑类型。当您将 1 加到一个指针上时,它会增加其类型的大小,在本例中为
sizeof(float)。
标签: c pointers memory-management