在C中填充数组

yfwxisqw  于 2023-03-22  发布在  其他
关注(0)|答案(2)|浏览(150)

我有一个关于在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]);
}

也许我试图解决它在一个太复杂的方式(我希望)。无论如何,一些方向,以帮助将是非常感谢。

0wi1tuuw

0wi1tuuw1#

#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
uxhixvfz

uxhixvfz2#

您应该替换以下行:

// 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。对于你原来的行,你只需要用一个“孤独”的空格“替换”以前的文本。

相关问题