我想传递一个指向函数的指针作为输出并在函数中初始化它,以便我可以在主函数中使用它。这是我的代码:
#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 之外使用此指针时,我收到“段错误(核心转储)”错误。
我正在使用 gcc 来编译我的代码。
最佳答案
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef const struct _txmlAttribute {
char * ns;
} txmlAttribute;
int func(txmlAttribute **attrsarr) {
txmlAttribute tattrs[] = {{"ssa"},{"ss"}};
if(NULL==(*attrsarr = malloc(sizeof(tattrs))))
return 0;
memcpy((void*)*attrsarr, tattrs, sizeof(tattrs));//const !
return 1;
}
int main(){
txmlAttribute *attrsarr;
func(&attrsarr);//update const object!
printf("main: attrs1: %s\n", attrsarr[0].ns);
printf("main: attrs2: %s\n", attrsarr[1].ns);
free((void*)attrsarr);
return 0;
}
关于c - 在c中使用参数作为输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24712657/