6.087 Practical Programming in C, lec7

24 篇文章 0 订阅

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*数组则不存储任何对象。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值