简体   繁体   English

C:我为什么要声明一个指针?

[英]C: why should I declare a pointer?

It seems there are many questions of the form "should I declare X?"似乎有很多“我应该声明 X 吗?”形式的问题。 but not this specific one.但不是这个特定的。 I hope it is ok to ask this.我希望可以问这个问题。

The title says it all: why should I declare a pointer?标题说明了一切:我为什么要声明一个指针? Even better: there are risks if I do not declare the pointer?更好的是:如果我不声明指针会有风险吗? Consider the following examples:考虑以下示例:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include <time.h>
#include <string.h>

void func(int *ptr);

int main (int argc, char **argv)
{

  int a;
  int *PTRa;

  a = -1;
  PTRa = &a;


  func(PTRa);
  printf("%d\n", a);

  return 0;

}

void func(int *ptr)
{
  *ptr = 1;
  return;
}

I get a=1 .我得到a=1 In this case I would say the pointer is declared (and assigned as well): I have the line int *PTRa;在这种情况下,我会说指针已声明(并且也已分配):我有行int *PTRa; (declaration) and the line PTRa = &a; (声明)和行PTRa = &a; (assignment). (任务)。 The results is correct.结果是正确的。 I don't get any warning.我没有得到任何警告。

Imagine now to replace the main with the following:现在想象一下用以下内容替换main内容:

int main (int argc, char **argv)
{

  int a;

  a = -1;

  func(&a);
  printf("%d\n", a);

  return 0;

}

Here I do not declare the pointer but just give the address of a to func .这里我没有声明指针,只是将 a 的地址afunc The result is correct and I don't get warnings.结果是正确的,我没有收到警告。

My understanding is that the two approaches are identical: func always gets the same input, the address of a .我的理解是这两种方法是相同的: func总是得到相同的输入,即a的地址。 I would even dare to say that I feel the second approach to be better, as I feel it to be clearer and I feel the variable PTRa to be useless and somewhat redundant.我什至敢说我觉得第二种方法更好,因为我觉得它更清晰,而且我觉得变量PTRa无用且有些多余。 However, I always see codes where the first approach is used and I have the feeling I will be told to do so.但是,我总是看到使用第一种方法的代码,我感觉我会被告知这样做。 Why?为什么?

In this case there's no benefit in creating a separate pointer variable.在这种情况下,创建单独的指针变量没有任何好处。

It might be necessary in more complex cases, just like it's sometimes necessary to create variables of any other type.在更复杂的情况下可能需要它,就像有时需要创建任何其他类型的变量一样。

You are correct: there's no point in declaring a pointer in your example.你是对的:在你的例子中声明一个指针是没有意义的。 A pointer is just a variable that holds an address.指针只是一个保存地址的变量。 The cleaner approach is to pass directly the address of the variable: func(&a) instead of doing one extra step and declaring PTRa .更简洁的方法是直接传递变量的地址: func(&a)而不是做一个额外的步骤并声明PTRa

Note that not all cases are this simple.请注意,并非所有情况都如此简单。 For example, if you want to have an array of int s, but you want to be able to grow that array dynamically because you don't know how big it should be you have to declare a pointer:例如,如果您想要一个int数组,但您希望能够动态增长该数组,因为您不知道它应该有多大,您必须声明一个指针:

int count = ...; // get the count from the user, from a file, etc
int *list_of_ints = malloc(sizeof(int) * count);
if (list_of_ints == NULL)
{
    // malloc failed.
    printf("Not enough memory!\n");
    exit(1);
}

// Now `list_of_ints` has enough space to store exactly `count` `int`s

EDIT: as @paulsm4 pointed out in a comment, the question Why use pointers?编辑:正如@paulsm4 在评论中指出的那样,为什么使用指针这个问题? is a great source of information related to this topic.是与此主题相关的重要信息来源。

EDIT 2: one good reason to want a pointer to the address of a variable might be that you want a pointer inside a structure or array:编辑2:想要一个指向变量地址的指针的一个很好的理由可能是你想要一个结构或数组内部的指针:

struct foo
{
    int x;
};

struct bar
{
    int y;
    struct foo f;
};

struct bar b;
struct foo *ptr_foo = &b.f;

You can now work more easily with bf because you're just working with a struct foo .您现在可以更轻松地使用bf ,因为您只是在使用struct foo

From the title, I thought you're talking about pointer type, but actually, you are asking if declaring a variable is needed.从标题中,我以为您在谈论指针类型,但实际上,您是在询问是否需要声明变量。

  • Variable is a piece of memory, storing some numbers(bytes), and the type of the variable, indicating how you and your program interpret those bytes: integer?变量是一块 memory,存储一些数字(字节)和变量的类型,指示您和您的程序如何解释这些字节:integer? float?漂浮? character?特点? etc.等等
  • Pointer is the memory address, it could be of a variable, or a function, or something else.指针是 memory 地址,它可以是变量,也可以是 function 或其他。
  • A variable of pointer is a small area in the memory, storing the address of other(or even same) memory.指针变量是 memory 中的一个小区域,存储其他(甚至相同)memory 的地址。
  • You decide if you need an extra variable to store the pointer.您决定是否需要一个额外的变量来存储指针。 It's the same to the decision that if you want a variable to store an integer:如果您想要一个变量来存储 integer,这与决定相同:
int v = -1;
abs(v); // use variable
abs(-1); // use constant

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM