我想将一个空指针数组传递给一个函数,该函数用可以正常工作的结果填充它,integer
但是返回时遇到麻烦char*
int function(void *arr[]);
int main(void) {
void *arr[3];
function(arr);
printf("%d\n", *(int *)&arr[0]);
printf("%d\n", *(int *)&arr[1]);
printf("%s\n", (char *)&arr[2]);
}
int function(void *arr[]){
arr[0] = (void*)(int)4;
arr[1] = (void*)(int)6;
char* test = "abc";
arr[2] = (void*)test;
return 0;
}
对于字符串我没有得到正确的值
您可以传递void
s数组,并将该数组元素分配给动态分配的存储区域,该区域存储指向的值。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int function(void *arr[]){
arr[0] = malloc(sizeof(int));
if (arr[0] == NULL) goto ERR_MALLOC_0;
*(int*)arr[0] = 4;
arr[1] = malloc(sizeof(int));
if (arr[1] == NULL) goto ERR_MALLOC_1;
*(int*)arr[1] = 6;
const char *const test = "abc";
arr[2] = malloc(strlen(test));
if (arr[2] == NULL) goto ERR_MALLOC_2;
strcpy(arr[2], test);
return 0;
// remember about error checking
free(arr[2]);
ERR_MALLOC_2:
free(arr[1]);
ERR_MALLOC_1:
free(arr[0]);
ERR_MALLOC_0:
return -1;
}
int main(void) {
void *arr[3];
int err = function(arr);
if (err == -1) abort();
// & is the address of element, not it's element
printf("%d\n", *(int*)arr[0]);
printf("%d\n", *(int*)arr[1]);
printf("%s\n", (char*)arr[2]);
// remember to free memory
for (int i = 0; i < 3; ++i) {
// funny how we do not need to know the effective type
free(arr[i]);
}
}
但是,这种功能显然令人困惑,并且会导致很多很多错误和问题。相反,实际上只使用适当类型的变量:
#include <stdlib.h>
#include <string.h>
int function(int *val1, int *val2, char **string) {
*val1 = 3;
*val2 = 6;
const char *test = "abc";
*string = malloc(strlen(test));
if (*string == NULL) return -1;
strcpy(*string, test);
return 0;
}
int main(void) {
int val1;
int val2;
char *string;
int err = function(&val1, &val2, &string);
if (err == -1) abort();
printf("%d\n", val1);
printf("%d\n", val2);
printf("%s\n", string);
free(string);
}
如果您真的在为在不同的数据类型上实现一些虚拟表示和操作而努力,那么使用简单的“void
指针数组”将无济于事,因为这样的数组不知道所存储的值的基本类型是什么-您,作为一名程序员,必须知道该数组内部的内容(即arr[0]
anint
和arr[2]
a char*
),因此,您最好一开始就使用适当类型的变量。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句