开发者

argv problem, new to c

I am having trouble with argv.

meltcheck(argv[1]);

function:

int meltcheck(char a[])
{
        if(a != "a" && a != NULL)
        {
                char dir[600];
                strcpy(dir, "del ");
                strncat(dir, a, sizeof(a));
                dir[strlen(dir开发者_C百科)] = '\0';
                printf("\ndtmeltcheck: %s\n", dir);
                //system(dir);
        }

        return 0;
}

Sorry the code got all messed up when I tried to paste it. But the problem is that argv is only storing 4 characters, even if the string is > 4 characters. Why does this happen?


There are a number of problems here. First off, you cannot compare the contents of strings using == or != in C - that compares the pointer values, so a != "a" will always be TRUE. Also, dir[strlen(dir)] is always equal to '\0' by definition. And sizeof(a) is the size of a char * (i.e. 4), not the length of the data.

Your function should look something like this:

int meltcheck( char *a )
{
    if( a != NULL && strcmp( a, "a" ) != 0 ) {
        char dir[600];
        strcpy( dir, "del " );
        strcat( dir, a );
        printf( "\ndtmeltcheck: %s\n", dir );
        // system( dir );
        // note that you should be using the unlink() function here
    }
}


You can't use sizeof in this way on arrays passed as parameters to functions.

The reason is that when passing an array to a function in C, the array decays into a pointer to its first element. As a result, when you take sizeof(a), you get the size of the pointer, not the size of the array. In this case, it is the same as sizeof(char *), which on a 32-bit machine will be 4, as you observe.

You're also using strncat in a way it wasn't really intended, though. The point of the third parameter is to prevent a buffer overflow if strlen(a) is longer than the amount of space in the buffer you're copying into, in this case, dir. I think what you want is:

strncat(dir, a, 595); /** 600 - "dir " - \0 = 595 */

Because there is room for 595 more characters in dir.

Also note that you can't compare C strings using !=. Your if statement should use strcmp instead.


I think the problem is that sizeof(a) will return sizeof(char*) (the size of a poitner to a character) rather than the length of the character string a. So it is only copying four characters.


Use strlen instead of sizeof. Sizeof of a pointer will be 4 on a 32 bits platform.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜