-1

我正在努力寻找一种使用 for 在 char* 中编写字母的方法。如果我只需要使用一个字符表来做到这一点,那就是这样的

for(i=0;i<26;i++) {
    character[i] = 'a' + i;
}

但是我有一个请求 char * 的函数,所以我必须使用"something"而不是'something'. 你能帮助我吗?

谢谢!

编辑

抱歉我之前没有说清楚。看来我很累了。

XPM 结构如下:

struct XPM {

    unsigned int width;
    unsigned int height;
    unsigned char cpp;
    unsigned int ncolors;
    Color *colta;
    unsigned int *data[]; 
};

所以,我必须使用的功能如下:

void setXPMColor(XPM *imagine,
    unsigned int index,
    unsigned char r,
    unsigned char g,
    unsigned char b,
    char *charpattern) {

    imagine -> colta [ index ].r = r;
    imagine -> colta [ index ].g = g;
    imagine -> colta [ index ].b = b;
    imagine -> colta [ index ].pchars = charpattern;
}

在 main() 函数中,我有以下代码行:

    for( i = 0; i < NCOLORS; i++ ) {
        setXPMColor( image, i, 5 * i, 0, 0, SOMETHING);
    }

我可以在函数中放置什么东西,所以对于每个索引,我都会有不同的字符?(我正在考虑为每个条目添加一个新字母或任何类型的符号)。稍后我将不得不使用这些符号来生成图像。

所以,最后我想要这样的东西:

printf("%s\n", imagine->colta[0].pchars); //a
printf("%s\n", imagine->colta[1].pchars); //b
printf("%s\n", imagine->colta[3].pchars); //c
//etc

编辑2:

我必须生成一个将创建图像的 XPM 文件,所以我必须在文件中绘制字符。问题是给函数setXPMColor一个字符,因为如果我发送它它需要一个 char* 例如'a'它会说类型不匹配,该函数需要一个 char* 但它接收一个 int。它只有在我用块引号发送它的字母时才有效"a",但是我不能在每次迭代时增加字母。我希望它有帮助!

谢谢!

4

2 回答 2

1

A char* is a pointer to a single character, or an array of characters, you your existing code will work. Just make sure that the char* you're passing into the function is at least 26 elements long, otherwise you will modify memory outside the array (which may or may not crash your program).

You can create such an array like so:

char * my_character_array = (char*) malloc(26);
于 2014-02-27T23:44:49.407 回答
0

I'm not sure if this is what you are asking but I would try converting to and from Ascii http://web.cs.mun.ca/~michael/c/ascii-table.html

that will allow you to cycle through the letters like they were numbers

于 2014-02-27T23:44:36.860 回答