为什么要使用指针? [英] Why use pointers?

查看:47
本文介绍了为什么要使用指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个非常基本的问题,但在使用高级语言编写了几个项目之后,我才刚刚开始进行一些基本的 C++ 编程.

I know this is a really basic question, but I've just started with some basic C++ programming after coding a few projects with high-level languages.

基本上我有三个问题:

  1. 为什么在普通变量上使用指针?
  2. 我应该在何时何地使用指针?
  3. 如何在数组中使用指针?

推荐答案

  • 为什么在普通变量上使用指针?
  • 简短的回答是:不要.;-) 将在不能使用其他任何东西的地方使用指针.要么是因为缺乏适当的功能、缺少数据类型,要么是纯粹的性能.更多内容如下...

    Short answer is: Don't. ;-) Pointers are to be used where you can't use anything else. It is either because the lack of appropriate functionality, missing data types or for pure perfomance. More below...

    • 我应该在何时何地使用指针?

    这里的简短回答是:您不能使用其他任何东西的地方.在 C 中,您不支持复杂的数据类型,例如字符串.也没有办法通过引用"将变量传递给函数.这就是你必须使用指针的地方.你也可以让它们指向几乎任何东西,链表,结构的成员等等.但我们不要在这里讨论.

    Short answer here is: Where you cannot use anything else. In C you don't have any support for complex datatypes such as a string. There are also no way of passing a variable "by reference" to a function. That's where you have to use pointers. Also you can have them to point at virtually anything, linked lists, members of structs and so on. But let's not go into that here.

    • 如何在数组中使用指针?

    用很少的努力和很多混乱.;-) 如果我们谈论诸如 int 和 char 之类的简单数据类型,则数组和指针之间几乎没有区别.这些声明非常相似(但不一样——例如,sizeof 将返回不同的值):

    With little effort and much confusion. ;-) If we talk about simple data types such as int and char there is little difference between an array and a pointer. These declarations are very similar (but not the same - e.g., sizeof will return different values):

    char* a = "Hello";
    char a[] = "Hello";
    

    你可以像这样访问数组中的任何元素

    You can reach any element in the array like this

    printf("Second char is: %c", a[1]);
    

    索引 1,因为数组从元素 0 开始.:-)

    Index 1 since the array starts with element 0. :-)

    或者你也可以这样做

    printf("Second char is: %c", *(a+1));
    

    指针运算符(*)是必需的,因为我们告诉 printf 我们要打印一个字符.如果没有 *,将打印内存地址本身的字符表示.现在我们改为使用角色本身.如果我们使用 %s 而不是 %c,我们会要求 printf 打印 'a' 指向的内存地址的内容加一(在上面的这个例子中),我们就不必把 *前面:

    The pointer operator (the *) is needed since we are telling printf that we want to print a character. Without the *, the character representation of the memory address itself would be printed. Now we are using the character itself instead. If we had used %s instead of %c, we would have asked printf to print the content of the memory address pointed to by 'a' plus one (in this example above), and we wouldn't have had to put the * in front:

    printf("Second char is: %s", (a+1)); /* WRONG */
    

    但这不会只打印第二个字符,而是打印下一个内存地址中的所有字符,直到找到空字符 ().这就是事情开始变得危险的地方.如果您不小心尝试使用 %s 格式化程序打印整数类型的变量而不是字符指针怎么办?

    But this would not have just printed the second character, but instead all characters in the next memory addresses, until a null character () were found. And this is where things start to get dangerous. What if you accidentally try and print a variable of the type integer instead of a char pointer with the %s formatter?

    char* a = "Hello";
    int b = 120;
    printf("Second char is: %s", b);
    

    这将打印在内存地址 120 上找到的任何内容,并继续打印直到找到一个空字符.执行这个 printf 语句是错误和非法的,但无论如何它可能会起作用,因为在许多环境中指针实际上是 int 类型.想象一下,如果您改用 sprintf() 并以这种方式将太长的字符数组"分配给另一个变量,则可能会导致的问题,这仅分配了一定的有限空间.您很可能最终会覆盖内存中的其他内容并导致程序崩溃(如果幸运的话).

    This would print whatever is found on memory address 120 and go on printing until a null character was found. It is wrong and illegal to perform this printf statement, but it would probably work anyway, since a pointer actually is of the type int in many environments. Imagine the problems you might cause if you were to use sprintf() instead and assign this way too long "char array" to another variable, that only got a certain limited space allocated. You would most likely end up writing over something else in the memory and cause your program to crash (if you are lucky).

    哦,如果你在声明 char 数组/指针时没有给它分配一个字符串值,你必须在给它一个值之前为其分配足够的内存量.使用 malloc、calloc 或类似的.这是因为您只声明了数组中的一个元素/一个指向的内存地址.举几个例子:

    Oh, and if you don't assign a string value to the char array / pointer when you declare it, you MUST allocate sufficient amount of memory to it before giving it a value. Using malloc, calloc or similar. This since you only declared one element in your array / one single memory address to point at. So here's a few examples:

    char* x;
    /* Allocate 6 bytes of memory for me and point x to the first of them. */
    x = (char*) malloc(6);
    x[0] = 'H';
    x[1] = 'e';
    x[2] = 'l';
    x[3] = 'l';
    x[4] = 'o';
    x[5] = '';
    printf("String "%s" at address: %d
    ", x, x);
    /* Delete the allocation (reservation) of the memory. */
    /* The char pointer x is still pointing to this address in memory though! */
    free(x);
    /* Same as malloc but here the allocated space is filled with null characters!*/
    x = (char *) calloc(6, sizeof(x));
    x[0] = 'H';
    x[1] = 'e';
    x[2] = 'l';
    x[3] = 'l';
    x[4] = 'o';
    x[5] = '';
    printf("String "%s" at address: %d
    ", x, x);
    /* And delete the allocation again... */
    free(x);
    /* We can set the size at declaration time as well */
    char xx[6];
    xx[0] = 'H';
    xx[1] = 'e';
    xx[2] = 'l';
    xx[3] = 'l';
    xx[4] = 'o';
    xx[5] = '';
    printf("String "%s" at address: %d
    ", xx, xx);
    

    请注意,在对分配的内存执行 free() 后,您仍然可以使用变量 x,但您不知道那里有什么.还要注意,两个 printf() 可能会给你不同的地址,因为不能保证第二次内存分配与第一次在相同的空间中执行.

    Do note that you can still use the variable x after you have performed a free() of the allocated memory, but you do not know what is in there. Also do notice that the two printf() might give you different addresses, since there is no guarantee that the second allocation of memory is performed in the same space as the first one.

    这篇关于为什么要使用指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆