gpt4 book ai didi

c - 读取命令行参数时出现段错误

转载 作者:行者123 更新时间:2023-12-05 01:36:35 26 4
gpt4 key购买 nike

#include<stdio.h>
#include<zlib.h>
#include<unistd.h>
#include<string.h>


int main(int argc, char *argv[])
{
char *path=NULL;
size_t size;
int index ;
printf("\nArgument count is = %d", argc);
printf ("\nThe 0th argument to the file is %s", argv[0]);
path = getcwd(path, size);
printf("\nThe current working directory is = %s", path);
if (argc <= 1)
{
printf("\nUsage: ./output filename1 filename2 ...");
}
else if (argc > 1)
{
for (index = 1; index <= argc;index++)
{
printf("\n File name entered is = %s", argv[index]);
strcat(path,argv[index]);
printf("\n The complete path of the file name is = %s", path);
}
}
return 0;
}

在上面的代码中,这是我运行代码时得到的输出:

$ ./output test.txt

Argument count is = 2
The 0th argument to the file is ./output
The current working directory is = /home/welcomeuser
File name entered is = test.txt
The complete path of the file name is = /home/welcomeusertest.txt
Segmentation fault (core dumped)

谁能帮我理解为什么我会收到核心转储错误?

最佳答案

您即将结束 argv通过说index <= argc .那应该是index < argc .请记住,数组索引从比数组长度少一

(您从 1 开始是正确的,因为 argv[0] 是程序名称。)

关于c - 读取命令行参数时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2556892/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com