`
jubincn
  • 浏览: 232064 次
  • 性别: Icon_minigender_1
  • 来自: 宁波
文章分类
社区版块
存档分类
最新评论

6.087 Practical Programming in C, lec7

 
阅读更多
<style type="text/css"> <!-- @page {margin:0.79in} p {margin-bottom:0.08in} h3 {margin-bottom:0.08in} h3.western {font-family:"Arial",sans-serif} h3.cjk {font-family:"AR PL UMing HK"} h3.ctl {font-family:"Lohit Hindi"} --> </style>

Pointers to pointers, pointer and string arrays, multidimensional arrays. Stacks and queues.



Pointer pointers

• What does this function do?

void swap (int ∗∗a , int ∗∗b){

int ∗temp = ∗a;

∗ a = ∗b;

∗b = temp;

}

• How does it compare to the familiar version of swap?

void swap ( int ∗a , int ∗b ){

int temp = ∗a;

∗a = ∗b;

∗b = temp;

}

第一个是交换了两个指针,内存中的数据并没有改变;第二个指针没变,但内存中的数据变了。

Pointer array

• Have an array int arr [100]; that contains some numbers

• Want to have a sorted version of the array, but not modify arr

• Can declare a pointer array int ∗ sorted_array[100];containing pointers to elements of arr and sort the pointers insteadof the numbers themselves

• Good approach for sorting arrays whose elements are very large(like strings)

struct的排序中,pointer会发挥很大的作用。

String arrays

• An array of strings, each stored as a pointer to an array ofchars

• Each string may be of different length

char str1[] = "hello"; /∗length = 6 ∗/

char str2[] = "goodbye";/∗ length = 8 */

char str3[] = "ciao"; /∗length = 5 ∗/

char ∗ strArray[ ] = { str1,str2, str3};

• Note that strArray contains only pointers, not the charactersthemselves

数组存储的不是字符,而是指针,因此要注意自动变量的作用域,如果是用malloc分配的堆内存,则需要注意free的时机。

Multidimensional arrays

• C also permits multidimensional arrays specified using []brackets notation:

int world [20][30]; is a 20x30 2-Darray of int’s

• Higher dimensions possible:

char bigcharmatrix [15][7][35][4]; –what are the dimensions of this?

• Multidimensional arrays are rectangular; pointer arrays can bearbitrary shaped

二维char数组和char*数组的区别?我想二维char数组在内存中是一块连续的空间,通过指针代数来获取其中元素的地址,char*数组则是一维数组,每个元素都是指针,两者最大的不同在于二维char数组中是存储对象的,而char*数组则不存储任何对象。




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics