gpt4 book ai didi

c - 为什么这2个char*变量的值在退出函数后没有改变?

转载 作者:太空宇宙 更新时间:2023-11-04 07:16:49 25 4
gpt4 key购买 nike

我正在编写一个 C 程序来乘以 2 个输入 vector 。这是代码:

/**
* Function name: parseArguments
* Description:
* Determine what options or arguments user used
* Command-line options:
* [-h] : Show help information
* [-n] num: Determine number of threads
* file1 : Choose first file
* file2 : Choose second file
* Return value:
* 0: If parsing successful
* exit: If error
**/
static int parseArguments(int argc, char **argv, int* nthreads, char* file1, char* file2)
{
int opt;
int help=0;
extern int optind;
extern char * optarg; // (global variable) command-line options

while ((opt = getopt(argc, argv, "hn:")) != EOF)
{
switch (opt) {
//Parse option -h, -n
case 'n':
*nthreads = atoi(optarg);
break;
case 'h':
Usage();
exit(1);
break;
default:
fprintf(stderr, "Try 'mulvector -h' for more information\n");
exit(1);
}


// parse file1 & file2 arguments
// THIS IS WHAT I'M ASKING
if (optind < argc)
{
file1 = &argv[optind];
optind++;
}
if (optind < argc)
file2 = &argv[optind];
}

return 0;
}

问题是,在我调用这个函数(在 main() 函数中)然后退出这个函数(继续 main() 函数)之后,2 个变量 file1 和 file2 在执行 parseArguments 之前仍然保持它们的旧值功能。我正在尝试解决此问题,但没有得到任何结果 ...

希望大家帮忙,先谢过了!

注意: file1 和 file2 的类型是 char file1[1024] 所以我不能使用 char** 作为 parseArguments 函数的参数!

最佳答案

C 按值传递参数。因此,您对 file1file2 所做的修改只是对函数内部指针的本地副本的修改。调用者看不到这些更改。

您可能想要:

  1. 将文本复制到 file1file2 引用的缓冲区,或者
  2. file1file2 的地址传递给函数并修改调用者看到的值。

选项 1 如下所示:

static int parseArguments(..., char* file1, char* file2)
{
....
strcpy(file1, argv[optind]);
....
strcpy(file2, argv[optind]);
....
}

当然,这是要求缓冲区溢出。因此,传递缓冲区的长度以允许代码避免溢出也是明智的,例如通过使用 strncpystrncat。这里有一个很好的问题讨论:Why should you use strncpy instead of strcpy?

选项 2 如下所示:

static int parseArguments(..., char** file1, char** file2)
{
....
*file1 = &argv[optind];
....
*file2 = &argv[optind];
....
}

关于c - 为什么这2个char*变量的值在退出函数后没有改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23929443/

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