【问题标题】:use parameter as output in c在c中使用参数作为输出
【发布时间】: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


    【解决方案1】:
    #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 中通过引用调用:) @BLUEPIXY
    猜你喜欢
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    相关资源
    最近更新 更多