c - 在c中使用参数作为输出

标签 c memory-management heap-memory pass-by-reference

我想传递一个指向函数的指针作为输出并在函数中初始化它,以便我可以在主函数中使用它。这是我的代码:

#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/

相关文章:

c - K&R的练习2-6 : Do not understand input/output

c - C appln 中的 dlopen 和 dlclose 内存管理

c - 内存分配和内存泄漏: C

c++ - 如何在 C++ 中的堆上使用位集?

c - 处理记录长度非常大的大型平面数据文件

c - main.o :main. c:function main: 错误:未定义对 'variable_name' 的引用

c - 为什么 execve 忽略环境参数?

c - c中的堆栈内存布局

c++ - 使用指针和偏移量迭代 stucts 成员的 vector

c# - 对象中的值类型也存储在堆中吗?