【发布时间】:2015-04-04 13:14:30
【问题描述】:
我正在使用此代码...
#include <stdio.h>
int main(int argc,char *argv[]){
int i =0;
if (argc == 1){
printf("You have entered 1 argument and you suck \n");
}
else if (argc > 1 && argc<4){
for (i=0;i<4;i++){
printf("you have entered the following args %d.%s \n",(i),argv[i]);
}
printf("\n");
}
else{
printf("You have entered more than four arguments and you suck.\n");
}
return 0;
}
如果我将 for 循环从 for (i=0;i<4;i++) 更改为 for (i=0;i<7;i++),我会得到以下输出:
cam@cam:~/Desktop/D/c/c-code$ ./ex12 hi there
you have entered the following args 0../ex12
you have entered the following args 1.hi
you have entered the following args 2.there
you have entered the following args 3.(null)
you have entered the following args 4.XDG_VTNR=7
you have entered the following args 5.LC_PAPER=en_IN.UTF-8
you have entered the following args 6.ORBIT_SOCKETDIR=/tmp/orbit-cam
为什么没有错误?为什么会生成这些与我的操作系统相关的变量?
【问题讨论】:
-
我的问题是为什么环境变量?我知道索引超出范围。我故意更改它以查看会发生什么
-
任何事情都可能发生。代码可以打印你的环境变量,可以格式化硬盘,可以让独角兽在你的显示器前跳舞等等。未定义的行为未定义。