与输入字符指针与字符数组 [英] Input with char pointer vs. char array
问题描述
考虑code
#include<stdio.h>
int main(void)
{
char* a;
scanf("%s",a);//&a and &a[0] give same results-crashes
printf("%s",a);
return 0;
}
为什么在这个崩溃code的结果?而使用字符数组这个code正常工作?
why does this code results in crashing?whereas this code using character array works fine?
#include<stdio.h>
int main(void)
{
char a[100];
scanf("%s",&a[0]);//works fine
printf("%s",a);
return 0;
}
区别在于字符数组和指针,但我知道,指针正好指向是与放大器的第一个元素; A [0]应该工作正常,但上code崩溃所有三个那就是,和放大器;一个和&放大器;一个[0]?
最主要的,我会收集是我如何可以采取一个字符指针的输入,如果我坚持只能用scanf函数?
我道歉,如果我不明白。
在此先感谢:)
the difference being character array and pointer?but i knew that pointer just points to the first element that is &a[0] should work fine but upper code crashes for all three that is a,&a and &a[0]? the main thing i would to gather is how can i take input of a character pointer if i insist on using scanf only? i apologize if i am not clear. thanks in advance:)
推荐答案
由于的char * A;
分配堆栈的字符指针,而烧焦[100];
为100个字符分配空间
Because char* a;
allocates space on the stack for a character pointer whilst char a[100];
allocates space for 100 characters.
在前者的情况下,你需要分配一定的实际的内存的指针指向。发生了什么事使你崩溃的是, A
被设置为某个任意值(你不初始化它),当你 scanf函数
,这是该数据被写入的位置。那如果你只是使用 A
,让我们叫那一声类型号之一。
In the former case, you need to allocate some actual memory for the pointer to point to. What's happening to cause your crash is that a
is being set to some arbitrary value (you don't initialise it) and, when you scanf
, that's where the data is being written. That's if you just use a
, let's call that crash type number one.
如果您使用&放大器;一个
,它会写在指针本身,这将让你与点谁也不知道的,其中一个指针您的输入,从而导致崩溃输入两个数字。这是假设你没有输入的字符数大于将溢出的指针 - 这会破坏调用堆栈导致没有的其他的死机的情况(三类)
If you use &a
, it will write your input over the pointer itself which will leave you with a pointer that points who-knows-where, leading to crash type number two. That's assuming you haven't entered more characters than will overflow the pointer - that would corrupt the call stack leading to yet another crash situation (type three).
和作为一句忠告,请不要使用没有边界检查,除非你控制是绝对以什么数据psented他们$ P $输入功能。即使有一个的char [100]
,有人可能会比将适合您的缓冲区中输入更多的字符会导致你的code堆栈溢出。
And as a word of advice, please don't use input functions that don't have bounds checking unless you're absolutely in control as to what data is presented to them. Even with a char[100]
, someone could cause a stack overflow in your code by entering more characters than will fit in your buffer.
我觉得做的最好的事情就是用与fgets
(其中可以的限制字符读)连同 sscanf的
(虽然如果所有你得到是一个字符串,的sscanf
是不是真的需要)。
I find the best thing to do is to use fgets
(which can limit the characters read) in conjunction with sscanf
(although if all you're getting is a string, sscanf
is not really needed).
这篇关于与输入字符指针与字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!