在char指针中输入字符串
#include #include #include int main(){ char *s; printf("enter the string : "); scanf("%s", s); printf("you entered %s\n", s); return 0; }
当我提供长度不超过17个字符的小输入时(例如“aaaaaaaaaaaaaaa”),程序工作得非常好,但是在提供更大长度的输入时,它会给我一个运行时错误,说“main.c已经意外停止工作”。
我的编译器(代码块)或我的电脑(Windows 7)有问题吗? 或者它是否以某种方式与C的输入缓冲区相关?
它是未定义的行为,因为指针未初始化。 您的编译器没有问题,但您的代码有问题:)
在将数据存储在那里之前指向有效的内存。
要管理缓冲区溢出,可以在格式说明符中指定长度:
scanf("%255s", s); // If s holds a memory of 256 bytes // '255' should be modified as per the memory allocated.
GNU C支持非标准扩展,如果指定了%as
但是应该传递指针指针,则不必分配内存,因为分配完成了:
#include #include 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; }
char指针未初始化,你应该动态地为它分配内存,
char *s = malloc(sizeof(char) * N);
其中N是您可以读取的最大字符串大小,并且在不指定输入字符串的最大长度的情况下使用scanf
不安全的,请像这样使用它,
scanf("%Ns",s);
其中N与malloc相同。
你没有为你的字符串分配内存,因此,你试图写入一个非授权的内存地址。 这里
char *s;
你只是在宣布一个指针。 您没有指定为字符串保留多少内存。 你可以静态地声明这个:
char s[100];
这将保留100个字符。 如果你超过100,它仍然会因为你再次提到同样的原因而崩溃。
您没有为字符数组分配任何内存,因此首先尝试通过调用malloc()或calloc()来获取内存。 然后尝试使用它。
s = malloc(sizeof(char) * YOUR_ARRAY_SIZE); ...do your work... free(s);
您需要为指针所指向的缓冲区分配足够的内存:
s = malloc(sizeof(char) * BUF_LEN);
如果你不再需要它,那么释放这个内存:
free(s);
问题在于您的代码..您永远不会为char *
分配内存。 因为,没有分配内存(使用malloc()
)足以容纳字符串,这将成为一个未定义的行为。
你必须为s
分配内存然后使用scanf()
(我更喜欢fgets()
)
在c ++中,您可以通过以下方式完成此操作
int n; cin>>n; char *a=new char[n]; cin >> a;
C中的代码读取字符指针
#include #include 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 }