我需要创建一个无符号整数数组一样如何从传递给脚本的参数中在c中创建一个无符号整数数组?
char** str_split(char* a_str, const char a_delim)
{
char** result = 0;
size_t count = 0;
char* tmp = a_str;
char* last_comma = 0;
char delim[2];
delim[0] = a_delim;
delim[1] = 0;
/* Count how many elements will be extracted. */
while (*tmp)
{
if (a_delim == *tmp)
{
count++;
last_comma = tmp;
}
tmp++;
}
/* Add space for trailing token. */
count += last_comma < (a_str + strlen(a_str) - 1);
/* Add space for terminating null string so caller
knows where the list of returned strings ends. */
count++;
result = malloc(sizeof(char*) * count);
if (result)
{
size_t idx = 0;
char* token = strtok(a_str, delim);
while (token)
{
assert(idx < count);
*(result + idx++) = strdup(token);
token = strtok(0, delim);
}
assert(idx == count - 1);
*(result + idx) = 0;
}
return result;
}
uint8_t in[] = {0X08,0X3c,0Xe6,0Xe3,0Xb9,0X74,0X4a,0Xdc,0Xd7,0X29,0Xee,0X99,0X35,0X15,0X8a,0X77};
从传递给脚本的参数。该参数将被传递给脚本就像
./conversion 0X08,0X3c,0Xe6,0Xe3,0Xb9,0X74,0X4a,0Xdc,0Xd7,0X29,0Xee,0X99,0X35,0X15,0X8a,0X77
我创建了下面的代码从
char** tokens;
tokens = str_split(argv[1], ',');
uint8_t hex[100];
uint8_t in[100];
if (tokens)
{
int i;
for (i = 0; *(tokens + i); i++)
{
printf("val=[%s]\n", *(tokens + i));
in[i] = *(tokens + i);
free(*(tokens + i));
}
printf("\n");
free(tokens);
}
for (i = 0; i < 16;i++)
printf("%02x ",in[i]);
我收到以下警告时,我执行的脚本参数创建数组
warning: assignment makes integer from pointer without a cast
但我能够打印出每个值使用
printf("val=[%s]\n", *(tokens + i))
但无法将其保存为数组,如
我的代码中是否有任何问题?你可以帮我吗 ?
谢谢Jean的回复。有没有什么办法像这样生成数组? –
甚至更好的是[mcve]。你的'str_split'方法丢失了,所以如果有人想为自己重现一个工作代码,他们就不能。 –
他不重用我可以看到的free()'d指针。他是免费的()'char *代币[i],而不是char **代币。由于我在free()之后迭代,它是一个不同的指针。 – torstenvl