将整数分配给C中的字符串

时间:2014-10-27 16:23:54

标签: c arrays string loops multidimensional-array

C中是否有一种方法可以用整数分配字符串。

我有一个2d的字符串数组,我知道它已经分配了索引,但我想为每个字符分配一个像id一样的随机数。 我不知道在将它提交到数组后或者直接阅读消息时是否应该这样做。

我想有类似的东西

2d阵列:

john  
michael  
simon  

我想要的是什么:

john - 234  
michael - 432  
simon - 489  

我的函数代码将名称插入数组

int store(char *stock){


    int r;
    static char test[5][10];
    static int i=0;
    int k,j=0;  


    //this just copies names from another function
    strcpy(test[i], stock);
    printf("%s in index:%d\n",test[i],i);

    qsort(test, i, 10, cmp);    
    if (i==4)
    {

        for (j = 0; j < 5; j++) {
            printf("%s\n",test[j]);
        }
    }
    i++;

}

感谢

3 个答案:

答案 0 :(得分:2)

您应该使用snprintf(3)(因为可能buffer overflows而避免旧的sprintf)。在GNU系统上,您可以使用asprintf(3)哪个堆分配一个字符串(另请参阅复制现有字符串的strdup(3))。

答案 1 :(得分:2)

您必须将整数转换为C中的字符串表示。

使用ltoa()/itoa()/_itoa_s()sprintf()/snprintf()

其次,如果它是一个缓冲区而不是一个指针,那么你无法分配它,你必须复制到它。

注意: 注意缓冲区溢出,更喜欢所有功能的安全版本。如果您的平台缺少 snprintf()或_itoa_s(),则使用sprintf()的安全方法是(1)避免无界格式字符串(%s等)和(2)识别你是什么格式化及其最大边界。

示例,对于64位整数:

最大值:

18,446,744,073,709,551,615

基数为10的ASCII长度为20个字符。对字符缓冲区使用大一个数量级。我喜欢使用1024长度的缓冲区进行sprintf()转换。

18446744073709551615 (unsigned) will be approx 20 length.

char buf[1024];
int64_t lval;
sprintf(buf, "%d", lval);
return strdup(buf);  // then dup it, or use strlen to malloc heap mem for your copy

答案 2 :(得分:0)

这是一个如何完成的例子

#include <stdio.h>
#include <string.h>

#define N 3
#define M 15

int main( void ) 
{
    static char test[N][M] = { "john", "michael", "simon" };
    unsigned int a[N] = { 234, 432, 489 };
    size_t i;

    for ( i = 0; i < N; i++ )
    {
        sprintf( test[i] + strlen( test[i] ), " - %u", a[i] );
    }

    for ( i = 0; i < N; i++ )
    {
        puts( test[i] );
    }

    return 0;
}

输出

john - 234
michael - 432
simon - 489

如果编译器支持sprintf,则可以使用snprintf而不是#include <stdio.h> #include <string.h> #define N 3 #define M 15 int main( void ) { static char test[N][M] = { "john", "michael", "simon" }; unsigned int a[N] = { 234, 432, 489 }; size_t i; for ( i = 0; i < N; i++ ) { size_t n = strlen( test[i] ); snprintf( test[i] + n, M - n, " - %u", a[i] ); } for ( i = 0; i < N; i++ ) { puts( test[i] ); } return 0; } 。例如

{{1}}