c - 无法打印 typedef 结构的 char* 类型字段
问题描述
以下代码将十进制转换为二进制并将其二进制表示存储到结构中。get_binary_representation()
可以正常工作,您可以通过取消注释打印val
. 但是,当我尝试打印存储在里面的二进制表示时,binary
什么都没有被打印出来。
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <stdbool.h>
typedef struct {
char* val;
int length;
} binary;
char* get_binary_representation(uint16_t val, int length) {
char* result;
if (length < 1)
return NULL;
if (val == 0) {
result = (char*) malloc(sizeof(char) * 2);
result[0] = '0';
result[1] = '\0';
return result;
}
result = (char*) malloc(sizeof(char) * length);
result[length - 1] = '\0';
for (int i = length; i > 0; i--) {
result[i] = ((val & 1) == 1) ? '1' : '0';
// printf("Bit %d = %c\n", i, result[i]);
val >>= 1;
}
return result;
}
binary i16_to_binary(uint16_t* val) {
binary result; // tried replacing it with pointer and using malloc, didn't help
result.val = get_binary_representation(*val, 16);
/* There is a function that finds length of number in binary
but I excluded it from MRE for simplicity sake.
16 for length because uint16_t is 16 bit integer*/
return result;
}
int main(int argc, char** argv) {
uint16_t a = 16; uint16_t b = 254; uint16_t c = 37;
binary a_bin = i16_to_binary(&a);
binary b_bin = i16_to_binary(&b);
binary c_bin = i16_to_binary(&c);
/* should print 0000 0000 0001 0000, 0000 0000 0111 1110, 0000 0000 0010 0101
without spaces and commas */
printf("%s %s %s\n", a_bin.val, b_bin.val, c_bin.val);
return 0;
}
解决方案
当心:
- 不要导致缓冲区溢出。只有索引
0
(length-1
包括两者)可用于带有length
元素的数组。result[i]
时超出范围i = length
。 - 初始化所有要读取的元素。
reuslt[0]
未初始化。 malloc()
家庭铸造结果被认为是一种不好的做法。
那个部分:
if (val == 0) {
result = (char*) malloc(sizeof(char) * 2);
result[0] = '0';
result[1] = '\0';
return result;
}
result = (char*) malloc(sizeof(char) * length);
result[length - 1] = '\0';
for (int i = length; i > 0; i--) {
result[i] = ((val & 1) == 1) ? '1' : '0';
// printf("Bit %d = %c\n", i, result[i]);
val >>= 1;
}
应该:
if (val == 0) {
result = malloc(sizeof(char) * 2); /* no casting the result */
result[0] = '0';
result[1] = '\0';
return result;
}
result = malloc(sizeof(char) * (length + 1)); /* no casting the result and allocate enough elements */
result[length] = '\0'; /* put NUL to proper place */
for (int i = length - 1; i >= 0; i--) { /* adjust the indice */
result[i] = ((val & 1) == 1) ? '1' : '0';
// printf("Bit %d = %c\n", i, result[i]);
val >>= 1;
}
推荐阅读
- php - laravel morphToMany 与数据透视表中的附加字段
- php - Ubuntu 18.04 LTS 中 php 7.0 中的 pthread 设置
- c# - 从 Lucene.Net 中的多个表中索引数百万条记录
- javascript - Jquery追加/前置svg并查找子元素
- ios - 带有 UICollectionViewCell 的可重用 UITableViewCell
- workbox - Workbox routing.registerRoute 幂等性
- powershell - 尝试使用 Exchange Online 运行脚本,连接有效,Get-UnifiedGroup 有效,但 Set 不存在?
- swift - 一个包含所有扩展方法的 Swift 模块
- google-cloud-platform - 如何让 Google Cloud Build 在响应 GitHub 触发器时正确替换值?
- c# - Tcp 监听器与 Http 监听器