打印字符数组,当有问题? [英] Having issues when printing an array of chars?

查看:109
本文介绍了打印字符数组,当有问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为我真的不明白我有整体的问题,它已经成为很难调试。

Since I don't really understand the overall issue I am having, it's become very difficult to debug.

char *o_key_pad = (char*)malloc(SHA256_DIGEST_LENGTH*sizeof(char));
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++){
    o_key_pad[i] = 'a';
}
printf("%s\n", o_key_pad);

char *i_key_pad = (char*)malloc(SHA256_DIGEST_LENGTH*sizeof(char));
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++){
    i_key_pad[i] = 'b';
}

printf("%s\n", o_key_pad);
printf("%s\n", i_key_pad);

和我得到的输出:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

为什么阵'o_key_pad得到扩展,包括无论我把阵'i_key_pad',好像某种内存问题的?

Why does the array 'o_key_pad' get extended to include whatever i put in array 'i_key_pad', seems like some sort of memory issue?

注:我明白,它可以更有效,但更清楚地显示我的观点,我把它像这样做。

Note: I understand that it can be done more effectively but to show my point more clearly I have laid it out like this.

推荐答案

的printf 不知道在哪里停止,除非您正确空终止字符串。 C风格的字符串如下(下面两行是等价的;在引号写一个字符串[字符串字面]会自动创建一个空结束的字符数组):

printf doesn't know where to stop unless you properly null-terminate your strings. C-style strings are as follows (the following two lines are equivalent; writing a string in quotes [a "string literal"] automatically creates a null-terminated character array):

char str[] = "hello world";
char str2[] = { 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '\0' };

这是您的code应该是什么样子:

This is what your code should look like:

int i;
char *o_key_pad = malloc(SHA256_DIGEST_LENGTH * sizeof (char) + 1);
for (i = 0; i < SHA256_DIGEST_LENGTH; i++) {
    o_key_pad[i] = 'a';
}
o_key_pad[i] = '\0';
printf("%s\n", o_key_pad);

char *i_key_pad = malloc(SHA256_DIGEST_LENGTH * sizeof (char) + 1);
for (i = 0; i < SHA256_DIGEST_LENGTH; i++) {
    i_key_pad[i] = 'b';
}
i_key_pad[i] = '\0';

printf("%s\n", o_key_pad);
printf("%s\n", i_key_pad);

这篇关于打印字符数组,当有问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆