简体   繁体   中英

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.

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数组的指针。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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