c char字符指针 [英] C Char pointers
问题描述
让我们说我们有一个指针数组:
的char * PTR [30];
现在这个工作得很好,而且似乎并不做任何意外!
我可以输入名字很容易。
scanf函数(%S,PTR [1]);
scanf的(%S,PTR [2]);
scanf函数(%S,PTR [3]);的printf(%S \\ n,PTR [1]);
的printf(%S \\ n,PTR [2]);
的printf(%S \\ n,PTR [3]);
我的问题是,如果一个指针可以通过这种方式来存储姓名结束数使用,那么为什么使用malloc的?在这种情况下ptr的[1]不指向在输入而是以一个新的输入本身的字符。
对于例如,如果PTR有穆库尔,PTR [1]应指向'U'
如果未分配空间时,指针声明如下,有哪些限制?
解决方案
指针的无法的使用这样
记住,仅仅因为你的程序编译和运行,并不意味着它是正确的。在C语言中有一个全班同学称为未定义行为的错误,其中许多编译器会很乐意让你做无抱怨。这些措施包括覆盖了缓冲区,使用未初始化变量,或提领的指针不指向一个合法分配的内存块。表现出未定义行为的程序,甚至可能会出现正常工作有时 - 但他们通常很不稳定,容易发生崩溃
Let us say we have a array of pointers:
char *ptr[30];
Now this works fine, and doesn't seems to do anything unexpected! I can input names easily.
scanf("%s", ptr[1]);
scanf("%s", ptr[2]);
scanf("%s", ptr[3]);
printf("%s\n", ptr[1]);
printf("%s\n", ptr[2]);
printf("%s\n", ptr[3]);
My question is if a pointer can be used in this way to store end number of names, then why is malloc used.? and in this case ptr[1] does not point to the character in the input but to a new input itself. for eg if ptr has mukul, ptr[1] should point to 'u' and if space is not allocated when a pointer is declared like this, what are the limits.?
The pointer cannot be used that way. It might "work" for you sometimes by sheer chance, but using a pointer without allocating memory for it will cause undefined behavior - meaning that your program may behave erratically and give you unexpected results.
Remember, just because your program compiles and runs doesn't mean it is correct. In the C language there is a whole class of errors known as "undefined behavior", many of which the compiler will happily let you do without complaining. These include overwriting a buffer, using an uninitialized variable, or dereferencing a pointer that doesn't point to a legitimately allocated memory block. Programs that exhibit undefined behavior may even appear to work normally sometimes - but they are usually very unstable and prone to crash.
这篇关于c char字符指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!