printf的修改字符串 [英] printf modifying a string

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

问题描述

使用的printf 打印\\ 4unix \\ 5lancs \\ 2AC \\ 2uk \\ 0我发现,而不是在♦UNIX♣lancs☻ac☻uk,我收到垃圾(♫,►E|§Qh↕)。

Using printf to print "\4unix\5lancs\2ac\2uk\0" I find, instead of a print in the form of ♦unix♣lancs☻ac☻uk, I get garbage (♫ ,►E¦§Qh ↕).

我找不到一个这样的解释;我用下面的方法来tokenise的字符串:

I cannot find an explanation for this; I use the following method to tokenise a string:

/**
 * Encode the passed string into a string as defined in the RFC.
 */
char * encodeString(char *string) {
    char stringCopy[128];
    char encodedString[128] = "";
    char *token;

    /* We copy the passed string as strtok mutates its argument. */
    strcpy(stringCopy, string);

    /* We tokenise the string on periods. */
    token = strtok(stringCopy, ".");

    while (token != NULL) {
    	char encodedToken[128] = "";

    	/* Encode the token. */
    	encodedToken[0] = (char) strlen(token);
    	strcat(encodedToken, token);

    	/* Add the encodedString token to the encodedString string. */
    	strcat(encodedString, encodedToken);

    	/* Prepare for the next iteration. */
    	token = strtok(NULL, ".");
    }

    /* A null character is appended already to the encoded string. */

    return encodedString;
}

和以下code在我的司机tokenising时,打印结果unix.lancs.ac.uk

And the following code in my driver to print the result when tokenising "unix.lancs.ac.uk":

int main(int argc, char *argv[]) {
    char *foo = "unix.lancs.ac.uk";
    char *bar = encodeString(foo);

    printf("%s\n", bar);

    return 0;
}

如果我添加一个的printf 打印连接codedString 在年底连接codeSTRING 的方法,我没有得到垃圾打印出来(而♦UNIX♣lancs☻ac☻uk两次)

If I add a printf to print encodedString at the end of the encodeString method, I don't get garbage printed out (rather, ♦unix♣lancs☻ac☻uk twice).

(调试后我发现实际的内存内容被改变。)

(Upon debugging I notice the actual memory contents is changed.)

任何人都可以解释这种现象对我?

Can anyone explain this phenomenon to me?

推荐答案

您正在返回一个指向数组连接codedString ,这是本地连接codeString的()功能,并具有自动存储时间。

You are returning a pointer to the array encodedString, which is local to the encodeString() function and has automatic storage duration.

这记忆不再有效的函数退出后,这是什么原因造成您的问题。

This memory is no longer valid after that function exits, which is what is causing your problem.

您可以通过给修复连接codedString 静态存储时间:

You can fix it by giving encodedString static storage duration:

static char encodedString[128];

encodedString[0] = '\0';

(你可以不再使用初始化器清空阵列,因为静态存储持续时间阵列从功能到下一次调用保持它们的值。)

(You can no longer use the initialiser to empty the array, because arrays with static storage duration maintain their values from one invocation of the function to the next.)

这篇关于printf的修改字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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