我有一个关于用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]);
}
也许我试图以太复杂的方式解决它(我希望)。无论如何,一些帮助的方向将受到高度赞赏。
答案 0 :(得分: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
。使用原始行,您只能用“孤独”空间“替换”以前的文本。
答案 1 :(得分:0)
#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