找到你要的答案

Q:When should I use a pointer to assign to an int?

Q:我什么时候应该使用指针赋给一个int?

Why and when should I use one method or another? I am trying to learn more about pointers, but I cannot understand this kind of usage scenario.

int i = 12;
i += 1; // 13
i = 55; // 55

int x = 6;
int * y = &x;
*y += 1; // 7
*y = 91; // 91

I have researched this question already but could not find an answer, thus the post on SO. I am not asking the difference between what they do, I understand their effect on memory. I do not understand which should be used in the style of scenario above. The title was updated to reflect this misunderstanding.

为什么和什么时候我应该使用一种或另一种方法?我试图了解更多关于指针,但我不明白这种用法的情况。

int i = 12;
i += 1; // 13
i = 55; // 55

int x = 6;
int * y = &x;
*y += 1; // 7
*y = 91; // 91

我已经研究过这个问题,但找不到答案,所以帖子就这样。我不是问他们做什么的区别,我理解他们对记忆的影响。我不明白在上面的场景中应该使用哪种风格。标题更新,以反映这种误解。

answer1: 回答1:

I know my answer will raise many eyebrows here but I can relate the question you asked here, so replying.

To keep your programming simple you can avoid use of pointers as long as possible. Most of the programs you will write initially will not require pointers at all.

However, as you start writing complicated programs where you'll also need to keep the execution time as minimal as possible, you may want to use pointers.

Apart from time constraints, there are many other places where pointers will be used e.g. when you want to pass/return structures to/from a function. Because passing/returning structures as value will put load on stack.

However, pointers are complicated and you may want to avoid them for writing simple programs if you really don't have any limitation of memory/time in your system.

You can anyways google (or read some books) about pointers for more information.

我知道我的回答会引起很多人的不满,但我可以回答你在这里问的问题,所以回答。

为了保持你的编程简单,你可以避免使用指针尽可能长。大多数你最初编写的程序根本不需要指针。

然而,当您开始编写复杂的程序时,您还需要尽可能地保持执行时间,您可能需要使用指针。

除了时间限制外,还有许多其他地方会用到指针,例如当你想通过函数返回/返回结构时。因为传递/返回结构作为值将加载堆栈。

然而,指针是复杂的,你可能想避免他们编写简单的程序,如果你真的没有任何限制的内存/时间在您的系统中。

你可以无论如何谷歌(或阅读一些书籍)有关指针的更多信息。

answer2: 回答2:

the basic difference between * and & as follows: *-indicates the value of operator and &-indicate the address of operator

the basic difference between * and & as follows: *-indicates the value of operator and &-indicate the address of operator

c  pointers  variable-assignment