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

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

问题描述

我知道这是一个非常基本的问题,但我刚开始用一些基本的C ++程序编码的几个项目具有高级语言之后。

基本上我有三个问题:


  1. 为什么在正常使用的变量的指针?

  2. 何时何地我应该使用指针?

  3. 你如何使用指针与数组一起?


解决方案

    在正常的变量
  • 为什么使用指针?

简短的回答是:不。 ;-)指针将被使用,你不能用别的。这可能是因为缺乏相应的功能,丢失的数据类型或纯更流畅。更多...以下


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

在这里简短的回答是:如果你不能用别的。在C语言中你不必为复杂的数据类型,如String的任何支持。也有没有通过引用传递变量函数的方法。这就是你必须使用指针。你也可以让他们来指向几乎任何东西,链表,结构的成员等。但我们不要进入这里。


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

通过点点努力和很大的混乱。 ;-)如果我们谈论的简单数据类型,如int和char有一个数组和指针之间的差别不大。
这些声明非常相似(但不相同 - 例如,的sizeof 将返回不同的值):

 的char * A =你好;
所以char a [] =你好;

您可以这样数组中达成任何元素

 的printf(第二个字符是:%C一个[1]);

索引1,因为该数组始于元素0: - )

或者你也可以同样做到这一点。

 的printf(第二个字符是:%C,*(A + 1));

需要指针运算符(将*),因为我们是在告诉我们要打印字符的printf。如果没有*,再存储地址本身的presentation的字符会被打印出来。现在,我们正在使用的字符本身,而不是。如果我们使用%S代替%C,我们会问的printf打印内存地址的内容指向'A'加一(在本例以上),我们不会有把*在前面:

 的printf(第二个字符是:%S(A + 1)); / * WRONG * /

但是,这不会刚刚打印的第二个字符,而是在下一存储器地址的所有字符,直到一个空字符(\\ 0)被发现。这就是事情开始变得危险。如果你不小心尝试与%s的格式打印整数类型的变量,而不是一个字符指针的?

 的char * A =你好;
INT B = 120;
的printf(第二个字符:%S,B);

这将打印无论是在内存地址找到120,并继续打印,直到空字符被发现。这是错误的,违法执行此printf语句,但它可能会反正工作,因为一个指针实际上是在许多环境中类型为int。试想一下,如果你使用的sprintf()来代替,并分配这样太长字符数组到另一个变量,你可能导致的问题,只分配了一定的空间有限。你最有可能最终改写别人在记忆的东西,导致程序崩溃(如果你幸运的话)。

哦,如果你没有指定一个字符串值,当你把它声明的字符数组/指针,你必须给它一个值之前分配的内存足够量的它。使用malloc,释放calloc或类似。这因为你只在你的阵列/一个单一的内存地址在指向宣布一个元素。所以这里有一个例子:

 的char * X;
/ *分配6个字节的内存,我和X点的第一人。 * /
X =(字符*)malloc的(6);
X [0] =H;
X [1] ='E';
X [2] =L;
X [3] =L;
X [4] ='O';
X [5] ='\\ 0';
的printf(字符串\\%s \\的地址数:%d \\ n,X,X);
/ *删除存储的分配(预约)。 * /
/ *的字符指针x被仍然指向这个地址在内存中,但! * /
免费(X);
/ *与malloc相同,但在这里分配的空间被填充空字符!* /
X =(字符*)释放calloc(6,的sizeof(X));
X [0] =H;
X [1] ='E';
X [2] =L;
X [3] =L;
X [4] ='O';
X [5] ='\\ 0';
的printf(字符串\\%s \\的地址数:%d \\ n,X,X);
/ *和再次删除分配... * /
免费(X);
/ *我们可以设置在声明时的大小以及* /
炭XX [6];
XX [0] =H;
XX [1] ='E';
XX [2] =L;
XX [3] =L;
XX [4] ='O';
XX [5] ='\\ 0';
的printf(字符串\\%s \\的地址数:%d \\ n,XX,XX);

请注意,您仍然可以使用变量x已分配的内存进行免费()之后,但你不知道什么是在那里。还请注意,这两个printf()的可能给你不同的地址,由于存在该存储器的第二分配在同一个空间作为第一个被执行的任何保证。

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.

Basically I have three questions:

  1. Why use pointers over normal variables?
  2. When and where should I use pointers?
  3. How do you use pointers with arrays?

解决方案

  • Why use pointers over normal variables?

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...

  • When and where should I use pointers?

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.

  • How do you use pointers with arrays?

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]);

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

Or you could equally do this

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

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 */

But this would not have just printed the second character, but instead all characters in the next memory addresses, until a null character (\0) 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);

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).

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] = '\0';
printf("String \"%s\" at address: %d\n", 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] = '\0';
printf("String \"%s\" at address: %d\n", 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] = '\0';
printf("String \"%s\" at address: %d\n", xx, xx);

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天全站免登陆