我在C中的字符串填充功能不起作用? [英] My string padding function in C does not work?

查看:119
本文介绍了我在C中的字符串填充功能不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经尝试自己做过,但是失败了(我很想再做一次以学习,但是只需要一个示例程序就可以了).本质上,我希望表示一个二进制数,但是当然要用0填充到最接近的字节,因此我在这里找到了另一个问题的函数:

I had tried to do it myself but failed (I am tempted to do it again for learning but just need it for an example program). Essentially I wish to represent a binary number but padded of course to the nearest byte with 0's so I found a function on another question here:

char * string_pad(char * string, size_t padlen, char * pad) {
    size_t lenstring = strlen(string);
    size_t lenpad = strlen(pad);

    char * padded = (char*)malloc(lenstring + lenpad + 1);
    strncpy(padded, string, lenstring); /* copy without '\0' */
    padded += lenstring; /* prepare for first append of pad */
    for(padlen += 1; padlen > 0; padlen--, padded += lenpad)
        strncpy(padded, pad, lenpad);
    *padded = '\0';
    return padded;
}

我这样称呼它:

printf("Test: %s\n", string_pad(dec2bin(~myInt), 32, "0"));

不幸的是,它打印"Test:",但没有其他显示.如果您需要知道的话,我的dec2bin返回一个简单的char指针.

Unfortunately it prints "Test: " but nothing else. My dec2bin returns a simple char pointer by the way if you need to know.

什么似乎使它无能为力?

What seems to be causing it to do nothing?

为什么此函数只接受char * pad而不接受char pad,所以我只能用'0'填充它,"0"也会起作用吗,或者它会添加一个空终止符来将其拧紧或其他?

Why does this function accept char* pad and not char pad so I can do just pad it with '0', will "0" work too or does it add a null terminator screwing it up or something?

编辑:或者有人可以提供一个简单的示例(或我需要做的事情)来解决这个问题吗?这个代码片段似乎并不是那么好.

EDIT: Or can somebody provide a simple example (or what I need to do what) to pad left for this? This snippet does not appear to be all that good..

我当时想创建一个初始化为零的chararray,然后再复制二进制文件,但是如何使它工作却使我无所适从.

I was thinking of creating a chararray initialized to zero, then copying the binary after that, but how to make it work escaped me..

推荐答案

填充"在返回字符串时指向字符串的末尾.

"padded" points to the end of the string when you are returning it.

这篇关于我在C中的字符串填充功能不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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