This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center
                            
                        
                    
                
                                6年前关闭。
            
                    
我对C感到很糟糕,对strcpy遇到了麻烦。我正在尝试获取函数参数之一并将其存储在char数组中。运行此命令时,出现分段错误,但不知道为什么。我究竟做错了什么?谢谢!

struct bb_state {
    FILE *logfile;
    char *rootdir;
};

struct bb_state *bb_data;
bb_data = malloc(sizeof(struct bb_state));
strcpy(bb_data->rootdir, argv[argc-2]);

最佳答案

您必须为char* rootdir分配内存。

例:

int len=strlen(argv[argc-2])+1;
bb_data->rootdir=malloc(len);


然后,您可以执行以下操作:

strcpy(bb_data->rootdir, argv[argc-2]);

09-29 21:40