首页 > 解决方案 > struct 变量成员 null 仅用于一个实例

问题描述

我有以下代码 -

#include<stdio.h>
#include<assert.h>
#include <stdlib.h>

typedef unsigned char Byte;

typedef struct _big_num {
   int  nbytes;  // size of array
   Byte *bytes;  /// array of Bytes
} BigNum;

void initBigNum(BigNum *n, int Nbytes)
{
    n = malloc(sizeof(BigNum));
    assert(n != NULL);
    n->bytes = calloc(Nbytes, sizeof(char));
    assert(n->bytes != NULL);
    if (n -> bytes == NULL) {
        fprintf(stderr, "error\n");
    }
    n->nbytes = Nbytes;
    return;
}

int main() {

    BigNum num1;
    BigNum num2;

    initBigNum(&num1, 20);
    initBigNum(&num2, 20);

    if (num1.bytes == NULL) {
        fprintf(stderr, "num1->bytes is NULL\n");
    }

    if (num2.bytes == NULL) {
        fprintf(stderr, "num2->bytes is NULL\n");
    }

    return 0;
}

我使用gcc -std=c99 -Wall aa.c. 我正在使用 MacOS。

输出是num2->bytes is NULL

为什么只有 num2 部分显示为 NULL?为什么不是 num1?我尝试在网上搜索它,但我不确定我应该如何搜索它。

对于上下文,我试图在 C 中为一个项目设计一个小型 BigInt 库。但是,当我尝试在 strncpy 中使用第二个 num2 时,我总是会抛出 seg 错误。

我在上面最短的代码中复制了同样的东西。

标签: cgcc

解决方案


推荐阅读