1

我有一个关于用 C 中的值填充数组的问题。我有一个字符串,我想将它拆分成一个新字符串数组,每 14 个“节”长。

int main(int argc , char *argv[])
{
char string[]="50 09 00 00 98 30 e0 b1 0d 01 00 00 00 00 4f 09 00 00 98 30 c6 b1 0d 01 01 01 01 50 09 00 00 98 30 e0 b1 0d 01 00 00 00 00 4f 09 00 00 98 30 c6 b1 0d 01 01 01 01";

char delim[] = " ";
char *result = NULL;
char *strArray[1440] = {0};
int i = 0;
result = strtok(string, " ");

while (result) 
{
 strArray[i] = result;
 result = strtok( NULL, delim );
 i++;
}

// Now I have each 'section' of the original string in strArray[xx]

int z = 1022;
int c;
char arr[5000];
char *finalarr[100] = {0};
char buff[100];
int l = 0;

for(c=0;c<z;++c) 
{
  strcat(arr,strArray[c]);
  if (c % 14 == 13)
  {
     // print the value so far for check, this gives an output of 28 chars 
     puts(arr);
     // copy value of arr to buff
     ret = sprintf(buff,"%s", arr);
     // copy value of buff to instance of finalarr
     finalarr[l] = buff;
     // empty arr
     strcpy(arr," ");
    l++;
  }
}

// both have the same value (last value of arr)
printf("finalarr1 = %s\n",finalarr[1]);
printf("finalarr20 = %s\n",finalarr[20]);
}

也许我正试图以一种过于复杂的方式解决它(我希望如此)。无论如何,一些帮助的方向将不胜感激。

4

2 回答 2

1

您应该替换以下行:

 // copy value of arr to buff
 ret = sprintf(buff,"%s", arr);
 // copy value of buff to instance of finalarr
 finalarr[l] = buff;

和:

 finalarr[l] = strdup(arr);

因为您只需要复制存储在arr. buff不应该需要该变量。

和行:

 // empty arr
 strcpy(arr," ");

和:

 *arr = '\0';

因为您只需要“重置”字符串arr。使用您的原始行,您只需用“孤独”空间“替换”以前的文本。

于 2012-04-25T00:18:42.430 回答
1
#include <stdio.h>
#include <string.h>

int main(int argc , char *argv[])
{
    int i;
    int fcount=0;
    int acount=0;
    char string[]="50 09 00 00 98 30 e0 b1 0d 01 00 00 00 00 4f 09 00 00 98 30 c6 b1 0d 01 01 01 01 50 09 00 00 98 30 e0 b1 0d 01 00 00 00 00 4f 09 00 00 98 30 c6 b1 0d 01 01 01 01";
    char *finalarr[100];
    char arr[29]="\0";
    for (i=0;i<(strlen(string));i++)
    {
        if ((i+1)%3!=0)
        {
            strncpy(&arr[acount],&string[i],1);
            acount++;
            if (acount==28)
            {
                acount=0;
                arr[29]="\0";
                finalarr[fcount]=strdup(arr);
                fcount++;
            }

        }
    }
    printf("finalarr1 = %s\n",finalarr[0]);
    printf("finalarr1 = %s\n",finalarr[1]);
    printf("finalarr1 = %s\n",finalarr[2]);
    return 0;
}

结果:

finalarr1 = 500900009830e0b10d0100000000
finalarr1 = 4f0900009830c6b10d0101010150
finalarr1 = 0900009830e0b10d01000000004f
于 2012-04-25T01:02:47.837 回答