我正在运行以下程序,但出现错误:

First-chance exception at 0x0f32d440 (msvcr100d.dll) in c.exe: 0xC0000005: Access violation reading location 0x00000000.
Unhandled exception at 0x772815de in c.exe: 0xC0000005: Access violation reading location 0x00000000.
The program '[9048] c.exe: Native' has exited with code -1073741510 (0xc000013a).

这是密码
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[], char *env[]) //char *argv[]
{
int i;

printf("These are the %d command- line arguments passed to main:\n\n", argc);
if(strcmp(argv[1],"123")==0)
    {
        printf("success\n");
     }
else
for(i=0; i<=argc; i++)
    //if(strcmp(argv[1],"abc")==0)

    printf("argv[%d]:%s\n", i, argv[i]);
/*printf("\nThe environment string(s)on this system are:\n\n");
for(i=0; env[i]!=NULL; i++)
printf(" env[%d]:%s\n", i, env[i]);*/
system("pause");
}

问题应该是strcmp函数,但我不知道如何解决它。
有人能帮忙吗?

最佳答案

你至少有两个问题。
首先是这样做:

if(strcmp(argv[1],"123")==0)

不需要首先检查argc >= 2
其次是:
for(i=0; i<=argc; i++)

在这种情况下,您应该处理参数0argc - 1之间的包含参数。循环的作用是处理参数0argc并且argv[argc]总是NULL
以下程序说明了解决此问题的一种方法:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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

    printf ("These are the %d command-line argument(s) passed to main:\n", argc);
    if ((argc >= 2) && (strcmp (argv[1], "123") == 0)) {
        printf ("   success\n");
    } else {
        for (i = 0; i < argc; i++)  {
            printf ("   argv[%d] = [%s]\n", i, argv[i]);
        }
    }
    return 0;
}

您可以看到,只有在确保正确填充"123"之后,才能与argv[1]进行比较。此外,循环已更改为排除argv[argc],因为这不是参数之一。抄本如下:
pax> testprog
These are the 1 command-line argument(s) passed to main:
   argv[0] = [testprog]

pax> testprog 123
These are the 2 command-line argument(s) passed to main:
   success

pax> testprog a b c
These are the 4 command-line argument(s) passed to main:
   argv[0] = [testprog]
   argv[1] = [a]
   argv[2] = [b]
   argv[3] = [c]

关于c - 访问冲突读取位置0x00000000。与argv [],我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16953512/

10-11 21:14