【发布时间】:2014-07-12 11:52:08
【问题描述】:
我想将一个指向函数的指针作为输出传递并在函数中对其进行初始化,以便我可以在主函数中使用它。这是我的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef const struct _txmlAttribute
{
/** The namespace URL of the attribute qname, or NULL for no qualifier. */
char * ns;
} txmlAttribute;
int func(txmlAttribute* attrs, txmlAttribute** attrsarr, txmlAttribute*** arr){
int i;
txmlAttribute tattrs[] = {{"ssa"},{"ss"}};
printf("sizeof(tattrs): %d \n", sizeof(tattrs));
printf("sizeof(txmlAttribute): %d \n", sizeof(txmlAttribute));
attrs= malloc(2*sizeof(txmlAttribute));
printf("sizeof(attrs): %d \n\n", sizeof(attrs));
for(i=0;i<sizeof(tattrs)/8;i++){
printf("tattrs[%d]: %s \n", i, tattrs[i].ns);
memcpy((void*)&attrs[i],(const void*)&tattrs[i],sizeof(txmlAttribute));
}
printf("\n\n");
for(i=0;i<2;i++){
printf("attrs[%d]: %s \n", i,attrs[i].ns);
}
printf("\n\n");
printf("sizeof(attrs): %d \n\n", sizeof(attrs));
return 0;
}
main()
{
txmlAttribute*** arr;
txmlAttribute** attrsarr;
txmlAttribute* attrs;
printf("main: sizeof(attrs) : %d \n\n", sizeof(attrs));
func(attrs, attrsarr, arr);
//printf("main: attrs: %s\n",attrs[0].ns);
}
但是有两个问题: 1. 因为我打印了传递指针的大小,它仍然是 8,而我预计是 16。 2. 当我想在 main 之外使用这个指针时,我收到“Segmentation fault (core dumped)”错误。
我正在使用 gcc 来编译我的代码。
【问题讨论】:
标签: c memory-management heap-memory pass-by-reference