cannot copy command line argument to character pointer in C [duplicate]

做~自己de王妃 提交于 2020-03-05 00:22:40

问题


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;
}

This gives me

Segmentation fault (core dumped)

回答1:


You did not allocate memory where you are going to copy the argument pointed to by the expression argv[1].

Try the following

#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;
}

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;
}



回答2:


cmdarg is a Uninitialized pointer by declaration. We have to allocate dynamic memory for cmdarg to point to. Below is a sample code

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    char *cmdarg;

    cmdarg = malloc( 5 * sizeof(char));
    if(argc>1)
    {
            strcpy(cmdarg, argv[1]);
            printf("%s\n", cmdarg);
    }
    else
            cmdarg = NULL;
    free(cmdarg);
    return 0;
}

Output while running with argument ./a.out yes is yes.

Note: Size allocated should not be lesser while using strcpy(). Make sure to use strncpy()



来源:https://stackoverflow.com/questions/60237281/cannot-copy-command-line-argument-to-character-pointer-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!