假设我有一个这样的结构..
struct object{
int id;
char *name;
node *list_head; //a pointer to the head of a linked list
};
typedef struct object object;我静态地声明了一个结构变量。我必须通过值将其传递给一个函数,该函数将一个元素插入到temp_obj中的列表中,如下所示。
我们可以假设add_element和print_list函数工作正常。如果我在function_a之后打印列表,那么它将不会打印插入的元素。我认为这是因为我将结构作为一个值传递,所以在function_a中所做的更改不会反映到在function_a之前声明的结构。
但由于给定的接口,我必须通过值传递结构。在这种情况下,我可以做些什么来反映对原始结构的更改?
object temp_obj
function_a(temp_obj);
print_list(temp_obj.list_head);
void function_a(object obj){
//add an element to the list
int num = 1;
add_element(&obj.list_head, num);
}发布于 2012-11-22 12:52:30
你完蛋了!
如果你不能改变接口,那么就没有办法让“值传递”的行为像“引用传递”一样。
您可以选择更改接口以获取object *,或者让函数返回object (或object*) -所有这些选项都需要更改接口。
发布于 2012-11-22 13:26:28
你可以在不太繁重的条件下做这件事,但这是一种欺骗。
如果add_element()函数将新元素添加到列表的末尾,而不是列表的头部,并且如果您安排列表中有一个初始节点,那么您几乎可以这样做。
证明:
#include <assert.h>
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void err_exit(const char *fmt, ...);
typedef struct node node;
typedef struct object object;
struct object
{
int id;
char *name;
node *list_head; //a pointer to the head of a linked list
};
struct node
{
node *next;
object *data;
};
static void add_element(node **list, int value)
{
assert(list != 0);
object *new_objt = calloc(sizeof(object), 1);
node *new_node = calloc(sizeof(node), 1);
if (new_objt == 0 || new_node == 0)
err_exit("Out of memory in %s\n", __func__);
node *next = *list;
while (next->next != 0)
next = next->next;
next->next = new_node;
new_node->data = new_objt;
new_objt->id = value;
}
static void print_list(const node *list)
{
assert(list != 0);
node *next = list->next;
printf("List: ");
while (next != 0)
{
if (next->data != 0)
printf("%d ", next->data->id);
next = next->next;
}
printf("EOL\n");
}
static void function_a(object obj)
{
int num = 1;
add_element(&obj.list_head, num);
}
int main(void)
{
node temp_node = { 0, 0 };
object temp_obj = { 0, 0, &temp_node }; // Key trick!
print_list(&temp_node);
function_a(temp_obj);
print_list(&temp_node);
function_a(temp_obj);
print_list(&temp_node);
return 0;
}
static void err_exit(const char *fmt, ...)
{
int errnum = errno;
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
if (errno != 0)
fprintf(stderr, " (%d: %s)", errnum, strerror(errnum));
putc('\n', stderr);
exit(EXIT_FAILURE);
}编译
gcc -O3 -g -std=c99 -Wall -Wextra node.c -o node 输出:
List: EOL
List: 1 EOL
List: 1 1 EOL如果练习的目标是击败脑死亡接口,那么这个方法就可以绕过它。如果本练习的目标是创建一个可用的接口,那么您可能不会这样做;您需要将一个指向结构的指针传递到function_a()中,这样就可以更改list_head。
发布于 2012-11-22 12:54:24
您不能使用通过值传递,..you必须更改您的界面设计,并使用通过引用传递
https://stackoverflow.com/questions/13506062
复制相似问题