字符* P,和scanf [英] Char* p, and scanf

查看:187
本文介绍了字符* P,和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 [] =...分配足够的内存来保存里面的...键,可以改变(其内容我的意思)。

编辑:

一个很好的办法来避免 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屋!

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