0

假设我有一个结构

 struct integer
 {
     int a[10000];
 };

还有一个字符串 s.. 我做了一个函数..

struct integer* convert_integer(char* stringInt)
 {
     int i=0;
     struct integer* A;
     A = (struct integer*)malloc(sizeof(struct integer));
     for (i=((strlen(stringInt))-1);i>=0;i--)
     {
         (A->a)[i]=(int)stringInt[(strlen(stringInt))-1-i] - 48;
     }
     return A;
 }

如何找到数组中的元素数,即数组中已填充的元素数,以便我可以以相反的顺序打印数组(因为我已将字符串转换为数组以相反的顺序)..

4

2 回答 2

0

我不知道为什么你保留一个变量 i 与位置然后重新计算以倒序排列,这样的事情可以完成这项工作

struct integer* convert_integer(char* stringInt)
{
    int i=0, j=0;
    struct integer* A;
    A = (struct integer*)malloc(sizeof(struct integer));
    for (i=((strlen(stringInt))-1);i>=0;i--)
    {
        (A->a)[j++]=(int)stringInt[i] - '0';
    }
    /* ***********************************
     j has the number of elements, 
     also you could put another fild in the struct which indicates just that:
     struct integer
     {
        int count;
        int a[10000];
     };
     A->count = j;
    ************************************ */
    return A;
}
于 2013-08-03T18:23:53.970 回答
0

您可以向结构添加一个长度字段,也可以在数组的最后一个元素中放置一个值,例如字符串使用 0x0。然后,对于它的 sizeof,你要么只使用长度字段,要么读取并计数,直到你得到你的特殊字节。

于 2013-08-03T21:23:08.287 回答