C语言 在字符指针中获取字符串输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14707427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Taking string input in char pointer
提问by Nikunj Banka
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(){
char *s;
printf("enter the string : ");
scanf("%s", s);
printf("you entered %s\n", s);
return 0;
}
When I provide small inputs of length up to 17 characters (for example "aaaaaaaaaaaaaaaaa") the program works perfectly fine but on providing inputs of larger lengths, it gives me a runtime error saying "main.c has stopped working unexpectedly".
当我提供长度不超过 17 个字符的小输入(例如“aaaaaaaaaaaaaaaaa”)时,程序运行良好,但在提供更大长度的输入时,它给我一个运行时错误,提示“main.c 意外停止工作”。
Is there some problem with my compiler (codeblocks) or my pc (windows 7)? Or is it somehow related to the input buffer of C?
我的编译器(代码块)或我的电脑(Windows 7)有问题吗?或者它与C的输入缓冲区有某种关系?
回答by P.P
It's undefined behaviouras the pointer is uninitialized. There's no problem with your compiler but your code has problem :)
这是未定义的行为,因为指针未初始化。你的编译器没有问题,但你的代码有问题:)
Make spoint to valid memory before storing data in there.
s在将数据存储在那里之前,请指向有效内存。
To manage buffer overflow, you can specify the length in the format specifier:
要管理缓冲区溢出,您可以在格式说明符中指定长度:
scanf("%255s", s); // If s holds a memory of 256 bytes
// '255' should be modified as per the memory allocated.
GNU C supports an non-standard extension with which you don't have to allocate memory as allocation is done if %asis specified but a pointer to pointer should be passed:
GNU C 支持非标准扩展,如果%as指定了,则不必在分配时分配内存,但应传递指向指针的指针:
#include<stdio.h>
#include<stdlib.h>
int main() {
char *s,*p;
s = malloc(256);
scanf("%255s", s); // Don't read more than 255 chars
printf("%s", s);
// No need to malloc `p` here
scanf("%as", &p); // GNU C library supports this type of allocate and store.
printf("%s", p);
free(s);
free(p);
return 0;
}
回答by Rami Jarrar
the char pointer is not initialized, you should dynamiclly allocate memory to it,
字符指针未初始化,您应该动态地为其分配内存,
char *s = malloc(sizeof(char) * N);
where N is the maximum string size you can read, And its not safe to use scanfwithout specifying the maximum length for the input string, use it like this,
其中 N 是您可以读取的最大字符串大小,如果scanf不指定输入字符串的最大长度,使用它是不安全的,像这样使用它,
scanf("%Ns",s);
where N same as that for malloc.
其中 N 与 malloc 相同。
回答by akp
You are not allocating any memory to the character array so first try to get memory by calling malloc() or calloc(). then try to use it.
您没有为字符数组分配任何内存,因此首先尝试通过调用 malloc() 或 calloc() 来获取内存。然后尝试使用它。
s = malloc(sizeof(char) * YOUR_ARRAY_SIZE);
...do your work...
free(s);
回答by oleg_g
You need to allocate enough memory for buffer where your pointer will point to:
您需要为指针将指向的缓冲区分配足够的内存:
s = malloc(sizeof(char) * BUF_LEN);
and then free this memory if you do not need it anymore:
如果您不再需要它,然后释放此内存:
free(s);
回答by m0skit0
You're not allocating memory for your string, and thus, you're trying to write in a non-authorized memory address. Here
您没有为字符串分配内存,因此,您试图写入未经授权的内存地址。这里
char *s;
You're just declaring a pointer. You're not specifying how much memory to reserve for your string. You can statically declare this like:
你只是在声明一个指针。您没有指定为字符串保留多少内存。您可以静态声明如下:
char s[100];
which will reserve 100 characters. If you go beyond 100, it will still crash as you mentionned for the same reason again.
这将保留 100 个字符。如果你超过 100,它仍然会因为同样的原因再次像你提到的那样崩溃。
回答by Nagendra Reddy
In c++ you can do it in the following way
在 C++ 中,您可以通过以下方式进行
int n;
cin>>n;
char *a=new char[n];
cin >> a;
回答by Sai Ganesh Myneni
The code in C to read a character pointer
C中读取字符指针的代码
#include<stdio.h>
#include<stdlib.h>
void main()
{
char* str1;//a character pointer is created
str1 = (char*)malloc(sizeof(char)*100);//allocating memory to pointer
scanf("%[^\n]s",str1);//hence the memory is allocated now we can store the characters in allocated memory space
printf("%s",str1);
free(str1);//free the memory allocated to the pointer
}
回答by ganesh borkar
#include"stdio.h"
#include"malloc.h"
int main(){
char *str;
str=(char*)malloc(sizeof(char)*30);
printf("\nENTER THE STRING : ");
fgets(str,30,stdin);
printf("\nSTRING IS : %s",str);
return 0;
}
回答by Aniket Inge
The problem is with your code .. you never allocate memory for the char *. Since, there is no memory allocated(with malloc()) big enough to hold the string, this becomes an undefined behavior..
问题出在你的代码上……你从来没有为char *. 因为,没有分配(使用malloc())足够大的内存来保存字符串,这成为一个未定义的行为..
You must allocate memory for sand then use scanf()(I prefer fgets())
您必须为其分配内存s然后使用scanf()(我更喜欢fgets())

