C 字符指针 [英] C Char pointers

查看:18
本文介绍了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
", ptr[1]);
printf("%s
", ptr[2]);
printf("%s
", ptr[3]);

我的问题是如果可以以这种方式使用指针来存储名称的结束数,那么为什么要使用 malloc.?在这种情况下,ptr[1] 不指向输入中的字符,而是指向新的输入本身.例如,如果 ptr 有 mukul,ptr[1] 应该指向 'u'如果像这样声明指针时没有分配空间,那么限制是什么?

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.

请记住,仅仅因为您的程序编译并运行并不意味着它是正确的.在 C 语言中,有一整类错误被称为未定义行为",其中许多错误编译器会很乐意让您毫无怨言地去做.这些包括覆盖缓冲区、使用未初始化的变量或取消引用不指向合法分配的内存块的指针.表现出未定义行为的程序有时甚至看起来可以正常工作 - 但它们通常非常不稳定并且容易崩溃.

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 字符指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆