gpt4 book ai didi

在 C 中将 char 数组转换为整数数组

转载 作者:行者123 更新时间:2023-11-30 21:24:56 32 4
gpt4 key购买 nike

我有一个如下所示的字符数组:

[0, 10, 20, 30, 670]

如何将此字符串转换为整数数组?

这是我的数组

int i=0;
size_t dim = 1;
char* array = (char*)malloc(dim);

while (proc.available()){

array[i] = (char)proc.read();
dim++;
i++;
array = (char*)realloc(array,dim);

}

最佳答案

给定发布的代码,该代码无法编译:

    int i=0;
size_t dim = 1;
char* array = (char*)malloc(dim);

while (proc.available()){

array[i] = (char)proc.read();
dim++;
i++;
array = (char*)realloc(array,dim);

}

它可以通过以下方式变成可编译函数:

void allocateArray()
{
int i=0;
size_t dim = 1;
char* array = (char*)malloc(dim);

while (proc.available())
{

array[i] = (char)proc.read();
dim++;
i++;
array = (char*)realloc(array,dim);
}
}

然后重新安排,消除不必要的系统函数调用并添加错误检查:

char * allocateArray()
{
int i=0;
size_t dim = 1;
char* array = NULL;

while (proc.available())
{
char *temp = realloc(array,dim);
if( NULL == temp )
{
perror( "realloc failed" );
free( array );
exit( EXIT_FAILURE );
}

// implied else, malloc successful

array[i] = (char)proc.read();
dim++;
i++;
}
return array;
} // end function: allocateArray

上面有一些问题:

  1. 它只分配一个字符,而不管每个数组条目中的实际字符数。
  2. 它不会生成整数数组。
  3. 无法获取多个角色

我们可以通过以下方式解决其中一些问题:

  1. 修改函数:proc.read()以返回指向 NUL 的指针终止的字符串而不是单个字符
  2. 将该字符串转换为整数
  3. 在每次迭代时分配足够的新内存来保存整数

这将导致:

int * allocateArray()
{
int i=0;
size_t dim = 1;
int* array = NULL;

while (proc.available())
{
int *temp = realloc(array,dim*sizeof(int));
if( NULL == temp )
{
perror( "realloc failed" );
free( array );
exit( EXIT_FAILURE );
}

// implied else, malloc successful

array = temp;
array[i] = atoi(proc.read());
dim++;
i++;
}
return array;
} // end function: allocateArray

但是,仍然存在一些问题。具体来说,C 程序不能具有名为: proc.available()proc.read()

的函数

关于在 C 中将 char 数组转换为整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33898441/

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