将字符串分配给指针变量时会发生什么?

时间:2019-06-08 15:40:09

标签: c

我不明白ptr变量指向什么。它是x字符串的单个元素吗?整个字符串?

int x[]={10,20,30,40,50};
int *ptr=x;
printf("%d",*(ptr+2));
printf("%d",*(ptr)+2);

4 个答案:

答案 0 :(得分:1)

这将设置ptr别名x的情况。

x and ptr are aliased.

例如ptr[2] == x[2] == *(x + 2) == 30。但是,xptr在C编译器中不是同一对象;具体来说,编译器知道xsizeof x = sizeof(int) * 5而不是sizeof ptr = sizeof(int *)的大小。同样,x的类型衰减为constant pointer to intptr的类型为pointer to int;这意味着ptr++可以,但是x++却没有意义。

答案 1 :(得分:0)

输出为:- 30 12 ptr是指向x第一个元素的指针。

答案 2 :(得分:0)

指针指向一个内存地址。当声明int *ptr=x;并将其初始化为ptr时,将为x的第一个元素在内存中的起始地址分配一个内存地址。因此,如果x由三个4字节整数组成,这些整数包含十进制值10、20、30,并且第一个整数的最低字节地址从地址0x1010开始,则ptr将被赋值为0x1010, x占用的内存地址看起来像

Addr |1010|1011|1012|1013|1014|1015|1016|1017|1018|1019|101A|101B|
     +====+====+====+====+====+====+====+====+====+====+====+====+
Val  | 0A | 00 | 00 | 00 | 14 | 00 | 00 | 00 | 1E | 00 | 00 | 00 |
     +====+====+====+====+====+====+====+====+====+====+====+====+

(以上所有地址和值均以十六进制显示)

以上假设采用“小端”架构,例如Intel x86,其中多字节整数的低位字节存储在低位地址中。 (在内存中,多字节整数在内存中的其他排序在其他体系结构上使用,但在此不再赘述。)

我希望这会有所帮助。

答案 3 :(得分:-1)

指针指向地址。为了说服自己,您可以使用printf中的export class ViewSource { private viewName : string; private viewStruct : IViewStruct; private rows : any[]; private rowIndex : number|null; constructor(viewName : string) { const {newViewName, newViewStruct, newRows, newRowIndex} = this.getNewValues(viewName); this.viewName = newViewName; this.newViewStruct = newViewStruct; // Rest of initialization goes here } public setViewName = (viewName: string) => { const {newViewName, newViewStruct, newRows, newRowIndex} = this.getNewValues(viewName); // Rest of initialization goes here } privat getNewValues = (viewName) => { const newViewName = viewName; const newViewStruct = api.meta.get_view_struct(viewName); if (!newViewStruct) { throw new Error("Clould not load structure for view, name=" + (viewName)); } const newRows = []; const newRowIndex = null; return {newViewName, newViewStruct, newRows, newRowIndex}; } } 标志来打印数组不同元素的不同地址。

%p