无法将命令行参数复制到C中的字符指针 [英] cannot copy command line argument to character pointer in C
本文介绍了无法将命令行参数复制到C中的字符指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在获取要复制到字符指针的命令行参数。
I am taking command line argument which I am copying to my character pointer. but its giving me an error.
int main(int argc, char *argv[])
{
char *cmdarg;
if(argc>1)
strcpy(cmdarg, argv[1]);
else
cmdarg = NULL;
return 0;
}
这给了我
Segmentation fault (core dumped)
推荐答案
您没有在要复制表达式 argv [1]
指向的参数的地方分配内存。
You did not allocate memory where you are going to copy the argument pointed to by the expression argv[1]
.
尝试以下操作
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *cmdarg = NULL;
if( argc > 1 )
{
cmdarg = malloc( strlen( argv[1] ) + 1 );
if ( cmdarg != NULL ) strcpy( cmdarg, argv[1] );
}
// ... Some other code
free( cmdarg );
return 0;
}
如果您只想存储指针的值 argv [1]
然后写
If you want just to store the value of the pointer argv[1]
then write
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *cmdarg = NULL;
if( argc > 1 )
{
cmdarg = argv[1];
}
// ... Some other code
return 0;
}
这篇关于无法将命令行参数复制到C中的字符指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文