c - 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 错误。
我在上面最短的代码中复制了同样的东西。
解决方案
推荐阅读
- ios - 如何将启动屏幕状态栏颜色设置为白色?
- html - 删除表格中两行小按钮之间的空格
- regex - 用 CL-PPCRE 匹配行尾
- spring - HttpSecurity 配置不适用于 Spring 上的 Keycloak 适配器
- python - for 循环执行
- python - 导入脚本时如何在函数之间传递变量,sense self.function 在导入代码时不起作用
- amazon-ec2 - 无法在 AWS ssh 中建立主机的真实性
- java - 如何使用 Queue 元素填充 ComboBox?
- node.js - Node js socket.io 需要验证请求和服务器响应
- c# - XPATH 搜索下一个节点