我需要使用的一个函数需要一个向量参数,用于返回存储,签名如下:
char ***vvar我应该把什么东西传进去?之后如何访问元素?
发布于 2010-09-24 20:56:17
假设您想要一个创建字符串向量的函数。您可以这样定义它并调用它:
#include "stdio.h"
#include "stdlib.h"
void make_vector(char*** vvar)
{
/* We're going to create a vector of strings. */
char** vector = malloc(sizeof(char*) * 3 );
vector[0] = "Hello";
vector[1] = "world!";
vector[2] = NULL;
/* Now we give the address of our vector to the caller. */
*vvar = vector;
}
int main(void)
{
char** vector_of_strings = NULL;
make_vector(&vector_of_strings);
printf("%s\n", vector_of_strings[0]);
return 0; /* Memory leak is an exercise for the reader. :-) */
}(在本例中,让make_vector返回数组会更简单,但在更复杂的示例中,传递vector_of_strings的地址更合理。)
发布于 2010-09-24 21:00:18
我将假设向量将包含字符串,因为这对您描述的签名最有意义。由于您也没有给出任何代码,因此我将假定您需要调用的函数类似于:
/* This function creates a vector with room for 'length' strings and places it in 'vvar' */
void create_string_vector(int /* in */ length, char*** /* out */ vvar);由于函数希望能够更改vvar并将该更改反映在调用方中,因此您必须传递某个变量的地址,因此调用应如下所示
create_string_vector(my_length, &my_var);这需要处理一个级别的指针。
这就只剩下如何声明my_var的问题了。由于它将是一个大小未知的向量或数组,您需要将其声明为指针。字符串也是一种未知大小的字符数组,所以你也需要一个指针。这将导致声明
char* *my_var;元素访问是最简单的部分:您可以将my_var视为一个数组:
my_var[0] = "Hello";发布于 2010-09-24 20:52:08
从外观上看,这不是一个向量。
如果函数签名是函数(...,char *vvar,...)之类的东西,那么您的解决方案就不简单了。
您需要知道每个维度需要多少缓冲区空间,然后创建复杂的数组,如下所示:
int dim_1 = 5, dim_2 = 4, dim_3 = 10;
char ***buffer = malloc(sizeof(char**)*dim_1);
for (int i=0;i++;i<dim_1) {
char **buffer_2 = malloc(sizeof(char*)*dim_2);
for (int j=0;j++;j<dim_2) {
char *buffer_3 = malloc(dim_3);
buffer_2[j] = buffer_3;
}
buffer[i] = buffer_2;
}https://stackoverflow.com/questions/3787115
复制相似问题