#include <stdio.h>
#include <stdlib.h>
//helper function
int arguments(char filename [100], int argc , char ** argv )
{
int ret = (argc < 3) ? -1 : 1;
filename = argv[1];
return ret;
}
int main (int argc, char ** argv )
{
char * filename;
FILE *fp;
//fill the empty bucket in other function
int ret = arguments(filename, argc , argv);
if(ret == -1)
{
perror("Error, something occured.\n");
return EXIT_FAILURE;
}
printf("The file is called %s\n",filename);
return 0;
}
我只是试图将argv [1]的名称更改为它们给出的名称。但 它在函数arguments()中不起作用,我只是看了一下,发现它在argv [1]中正确读取,我认为我做对了
答案 0 :(得分:2)
您需要将filename
作为指向char
的指针的指针,
int arguments(char **filename, int argc , char ** argv )
{
int ret = (argc < 3) ? -1 : 1;
*filename = argv[1]; // char * = char *
return ret;
}
然后将其命名为
/**
* type of filename is char *, so type of &filename is char **
*/
int ret = arguments(&filename, argc , argv);
请记住,要使函数更改输入参数的值以使更改反映在调用函数中,必须将指针传递给该参数:
void foo( T *ptr ) // for any type T
{
*ptr = new_T_value(); // write a new value to the thing ptr points to
}
void bar( void )
{
T val;
foo( &val ); // update the value in val
}
对于指针类型也是如此-如果将T
替换为P *
,我们将得到:
void foo( P **ptr ) // for any type T
{
*ptr = new_Pstar_value(); // write a new pointer value to the thing ptr points to
}
void bar( void )
{
P *val;
foo( &val ); // update the pointer value in val
}
我们所做的只是将类型T
替换为类型P *
,但其他所有操作都相同。传递参数时,您仍然需要使用&val
,这意味着形式参数ptr
的间接寻址级别将比val
多,并且必须使用*ptr
分配新值。