我的c函数'strcpy'有问题,我无法弄清楚。
它涉及复制到像Argv(但实际上不是Argv)的char * []。我可以复制出结构,但不能复制。但只有我最初在一次性中声明整个Argv结构。
我假设char *[]
是char*
的数组。
以下是该问题的简单演示程序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char FN[]="BBBB";
char *TL[]={
"a0 ",
"a1 ",
"a2 ",
"a3 ",
"a4 ",
"a5 "};
char BN[]="c1 ";
char N0[]="N0 ";
char N1[]="N1 ";
char N2[]="N2 ";
char N3[]="N3 ";
char N4[]="N4 ";
char N5[]="N5 ";
char* TD[6];
int main ( int argc, char *argv[] )
{
// FN is a pointer to an array of chars
// BN is the same
//TL is an array of pointers (that each point to an array of chars)
//TL[1] is thus a pointer to an array of chars
//TL is the same structure as Argv
//TD is the same structure as Argv (but built up from parts)
// but is spread out across the globals and the main func.
// thus less easy to read and understand then TL.
//TL[i], TD[i], and BN are initially allocated significantly larger than FN
// to remove the worry of overruns.
//copy "a1 \0" into the space held by "c1 "
strcpy(BN,TL[1]); //works
//copy "BBBB\0" into the space held by "c1 "
strcpy(BN,FN); //works
TD[0]=N0;
TD[1]=N1;
TD[2]=N2;
TD[3]=N3;
TD[4]=N4;
TD[5]=N5;
//copy "BBBB\0" into the space held by "a1 "
strcpy(TD[1],FN); //works
//copy "BBBB\0" into the space held by "a1 "
//strcpy(TL[1],FN); //dies
}
答案 0 :(得分:4)
您的char
指针指向字符串文字。那些不可写。尽管出于历史原因他们的类型为char*
,但您应始终将其视为char const *
。
malloc
缓冲区的char
空间,或者使用数组数组。
答案 1 :(得分:1)
正如dasblinkenlight在上面评论中发布的链接
char * p = "xyz"; is different from
char p[] = "xyz";
第一个是不可变的,第二个是可变的。