当我们可以直接为它分配一个字符串时,为什么不能将一个字符串复制到“字符指针"中呢? [英] Why Can't we copy a string to Character Pointer WHEN we can assign a string directly to it?
问题描述
此代码产生"p = hello world":
This code produces "p = hello world":
#include "stdio.h"
#include "string.h"
int main(){
char *p;
p="hello world";
printf("p is %s \n",p);
return 0;
}
但是此代码会产生分段错误:
But this code produces a segmentation fault:
#include "stdio.h"
#include "string.h"
int main() {
char *p;
strcpy(p,"hello");
printf("p is %s \n",p);
return 0;
}
并且此代码产生"p = hello"
and this code produces "p = hello"
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
int main() {
char *p;
p=(char*)malloc (10);
strcpy(p,"hello");
printf("p is %s \n",p);
return 0;
}
推荐答案
在p="hello world";
(此编辑时为第一种情况)的情况下,p
初始化为指向 read-仅内存区域,其中包含字符串"hello world"(字符串文字).该只读内存区域是在编译时创建的.
In the case where p="hello world";
(1st case at the time of this edit), p
is being initialized to point to a read-only memory region which contains the string "hello world" (string literal). This read-only memory region is created at compile time.
在导致分段错误的情况下(此编辑时为第二种情况),p
未初始化,将任何内容复制到其中将产生不可预测的结果,因为p
指向的内存位置不是由代码指定.
In the case that causes the segmentation fault (2nd case at the time of this edit), p
is uninitialized and copying anything to it will produce unpredictable results because the location in memory that p
is pointing to is not specified by the code.
在将字符串复制到p
之前,必须指定p
指向的内存.
Before you can copy a string to p
, you must specify the memory that p
is pointing to.
您可以在堆栈上分配此内存
You can allocate this memory on the stack
char buf[BUFSIZ] = ""; /* local variable */
在堆上
char *buf = malloc(BUFSIZ); /* don't forget to free */
或__DATA段中.
static char buf[BUFSIZ] = ""; /* global variable */
然后可以初始化p
指向内存缓冲区.
You can then initialize p
to point at the memory buffer.
char *p = buf;
这在概念上类似于初始化p
以指向只读内存中的字符串文字.与p
指向字符串文字的情况不同,您现在可以将字符串复制到字符指针,因为它不指向只读内存.
This is similar in concept to initializing p
to point to the string literal in read-only memory. Unlike the case where p
points to the string literal, you can now copy a string to the character pointer as it does not point to read-only memory.
注意:我有意创建了一个单独的缓冲区,并初始化了p
指向它,以帮助阐明我的观点.
Note: I intentionally created a separate buffer and initialized p
to point to it to help make my point.
这篇关于当我们可以直接为它分配一个字符串时,为什么不能将一个字符串复制到“字符指针"中呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!