gpt4 book ai didi

c - strcpy 因 char *[] 崩溃(ARGV 结构)

转载 作者:行者123 更新时间:2023-11-30 18:26:16 26 4
gpt4 key购买 nike

我无法解决 c 函数“strcpy”的问题。

它涉及像 Argv 一样复制到 char *[](但实际上不是 Argv)。我可以从结构中复制出来,但不能复制进去。但前提是我最初一次性声明了整个 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



}

最佳答案

您的char指针指向字符串文字。这些是不可写的。即使由于历史原因它们的类型是 char*,您也应该始终将它们视为 char const *

char 缓冲区使用 malloc 空间,或者使用数组的数组。

关于c - strcpy 因 char *[] 崩溃(ARGV 结构),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18674491/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com