简体   繁体   English

指向C中数组的指针不起作用

[英]pointers to arrays in c not working

char (*ptr)[10];
scanf("%s",ptr);//inputing a string

Why is this not working? 为什么这不起作用? According to me this should work because ptr is a pointer to an array of characters. 对我来说,这应该起作用,因为ptr是指向字符数组的指针。

A pointer to an array is NOT an array, you have nowhere to put your characters. 指向数组的指针不是数组,您无处可放字符。

It's like having a doormat without a house, that doesn't mean you have somewhere to receive your guests. 这就像没有房子的门垫,这并不意味着您有可以接待客人的地方。

To have the above working you should 要进行上述工作,您应该

char ptr[10]; // This is where you have space, specifically stack space
char (*this_is_a_pointer_to_array)[10]; // This only holds space to keep an address to an array
this_is_a_pointer_to_array = &ptr;
scanf("%s",ptr);

although you don't really need the pointer to array in the case above. 尽管在上述情况下您实际上并不需要指向数组的指针。

A pointer to an array only holds as much space as necessary to hold the address to an array, there's no space to store anything else than an address. 指向数组的指针仅保留将数组的地址保存为数组所需的空间,除地址外没有其他空间可以存储。 If you horribly circumvent the typecasting mechanism you might use that space to store some characters instead of an address, but that is against every moral fiber of my body and probably against every typecasting rule as well. 如果您极力规避类型转换机制,则可以使用该空间来存储一些字符而不是地址,但这不符合我身体的每一个道德纤维,也可能违反所有类型转换规则。

ptr不是指向char的指针,而是指向10个char数组的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM