字符* P,和scanf [英] Char* p, and scanf
问题描述
我一直在试图寻找一个理由如下code失败了,我无法找到一个。
所以,请原谅我的无知,让我知道这里发生了什么。
#包括LT&;&stdio.h中GT;
诠释主要(无效){
的char * p =你好,这是行不通的;
scanf的(%S,P);
返回0;
}
据我理解,我创建一个指针p以一个连续的区域中的尺寸29 + 1的存储器(对于\\ 0)。
为什么我不能用scanf函数来改变的内容是什么?
P.S请纠正我,如果我说了一些错的char *。
的char * p =你好,这是行不通的;
这不分配内存为你写
这将创建一个字符串文字
这将导致未定义行为
每次尝试更改其内容的时间。
使用 P
作为一个缓冲你的 scanf函数
做这样的事情的char * p = malloc的(sizeof的(char)的* 128); // 128就是一个例子
或
您可以同时做的:
字符P [] =你好,这是行不通的;
我的猜测是你真正想做的事。
记记住,这仍然最终被 UB
,因为 scanf()的
不检查是否到位您正在使用的确是有效的写存储器。
记住:
的char * P
是一个字符串文字,不应该被修改
字符P [] =...
分配足够的内存来保存里面的...$ C字符串$ C>键,可以改变(其内容我的意思)。
编辑:
一个很好的办法来避免 UB
是
的char * p = malloc的(sizeof的(char)的* 128);
scanf的(%126S,S);
I have been trying to look for a reason why the following code is failing, and I couldn't find one. So please, excuse my ignorance and let me know what's happening here.
#include<stdio.h>
int main(void){
char* p="Hi, this is not going to work";
scanf("%s",p);
return 0;
}
As far as I understood, I created a pointer p to a contiguous area in the memory of the size 29 + 1(for the \0). Why can't I use scanf to change the contents of that?
P.S Please correct me If I said something wrong about char*.
char* p="Hi, this is not going to work";
this does not allocate memory for you to write
this creates a String Literal
which results inUndefined Behaviour
every time you try to change its contents.
to use p
as a buffer for your scanf
do something like
char * p = malloc(sizeof(char) * 128); // 128 is an Example
OR
you could as well do:
char p[]="Hi, this is not going to work";
Which I guess is what you really wanted to do.
Keep in mind that this can still end up being UB
because scanf()
does not check whether the place you are using is indeed valid writable memory.
remember :
char * p
is a String Literal and should not be modified
char p[] = "..."
allocates enough memory to hold the String inside the "..."
and may be changed (its contents I mean).
Edit :
A nice trick to avoid UB
is
char * p = malloc(sizeof(char) * 128);
scanf("%126s",s);
这篇关于字符* P,和scanf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!