动态构建在C字符 [英] Dynamically construct a char in C

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

问题描述

我试图构建有一系列的性格,我想在飞,构建一个数组,人物都是这样 \\ X01 \\ X02 等。

I am trying to construct an array that has a series of character that I want to construct in the fly, the characters are like this \x01, \x02 and so on.

举例来说,假设我们有:

For example, lets say we have:

#define NUMCOLORS 3
char delim[NUMCOLORS];

我们希望在 DELIM 的值 \\ X01 \\ X02 \\ X03

我觉得两种可能的方式做到这一点,但都引起段错误:

I thought two possible ways to do it, but both cause a segfault:

for (int i = 0; i < NUMCOLORS; i++){
  char *h = "\x01";
  sprintf(h, "\x0%d", i+1);
  strcpy(delim[i], h);
}

// Other way

for (int i = 0; i < NUMCOLORS; i++){ 
  char *h = "\x0";
  strcpy(delim[i], h+1);
}

有没有一种方法,我可以创建字符我需要

推荐答案

没有,请不要使用的strcpy ,因为它会增加一个字符串结束。此外,这样做 H + 1 给你下一个字符的字符串由 ^ h 这是一个字符串结束指出。

No, don't use strcpy as it will add the string terminator. Also, doing h + 1 give you the next character in the string pointed to by h which is the string terminator.

而是使用一个事实,即一个字符实际上是一个整数值。这意味着你可以做例如

Instead use the fact that a character is actually an integer value. That means you can do e.g.

char delim[4];

for (int i = 0; i < 3; ++i)
    delim[i] = i + 1;

/* Terminates as string */
delim[3] = '\0';

现在你可以使用 DELIM 在C其他任何字符串,包含字符串\\ 01 \\ 02 \\ 03

Now you can use delim as any other string in C, and contain the string "\01\02\03".

如果你想在字符串包含不是的字符'\\ 01''\\ 02'等,这时就需要一个更大的阵列,构建字符串的另一种方式:

If you want the string to contain not the characters '\01', '\02' etc, then you need a bigger array, and another way of constructing the string:

/* 3 sequences of 4 characters (backslash, x, two digits), plus terminator */
char delims[3 * 4 + 1] = { 0 };  /* Initialize to zero (the string terminator) */

for (int i = 0; i < 3; ++i)
{
    char temp[5];  /* Place for 4 characters plus terminator */
    sprintf(temp, "\\x%02d", i);

    strcat(delims, temp);
}

现在在这之后的的字符串 delims 将包含字符串\\ X01 \\ X02 \\ X03。请注意,反斜杠是真实的反斜杠,不是编译器将翻译,如果打印字符串到控制台输出将是正是,反斜杠全。

Now after this the string delims will contain the string "\x01\x02\x03". Note that the backslashes are real backslashes, not something that the compiler will translate, if you print the string to the console the output will be exactly that, backslashes an all.

这篇关于动态构建在C字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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