gpt4 book ai didi

c - 如何根据传递给脚本的参数在 c 中创建无符号整数数组?

转载 作者:行者123 更新时间:2023-11-30 14:54:53 24 4
gpt4 key购买 nike

我需要创建一个无符号整数数组,例如

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))

但无法将其保存为数组,例如

我的代码有什么问题吗?你能帮我吗?

最佳答案

请记住,tokens 是指针到指针类型,char **tokens。因此*(tokens+i)是一个指针。您将该指针(指向字符串)视为整数。

您需要做的就是首先将字符串转换为整数类型。 strtoul() 是一个很好的起点。您甚至可以指定您的基数,以便它自动为您从十六进制转换。

for (i = 0; tokens[i]; i++)
{
char *endptr;
unsigned long tmp;
printf("val=[%s]\n", tokens[i]);
tmp = strtoul(tokens[i], &endptr, 16);
if (endptr == tokens[i]) {
/* end of valid number is the beginning of the string */
/* that means there was no valid number */
/* insert error handling here (e.g. reprinting usage) */
in[i] = (uint8_t)0;
} else {
in[i] = (uint8_t)tmp;
}
free(tokens[i]);
}

关于c - 如何根据传递给脚本的参数在 c 中创建无符号整数数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46439263/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com