gpt4 book ai didi

c - 将 char 数组中的信息放入动态创建的数组中

转载 作者:太空宇宙 更新时间:2023-11-04 07:28:16 25 4
gpt4 key购买 nike


  1. 我正在尝试从一个 char string 传递信息使用“.”标记化作为集合。
  2. 使用 atoi()
  3. 将这些字符转换为 整数
  4. 然后将值发送到动态分配的内存

我知道这个理论,我知道它应该如何工作,但我无法获得使其工作的正确语法!

第二部分,在我声明 *Malloc_Array_ptr* 之后遇到了麻烦。到目前为止,我使用 Malloc 指针的方式与使用常规数组指针的方式完全相同,但我的 printf 测试没有得到任何结果。

在谷歌上找不到对我有意义的信息,我快要疯了。我想我真的快弄清楚了,我只需要朝着正确的方向轻推 >.<

谢谢! :)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 10
#define MIN_SIZE 2


void StrInput(char str[], int maxChars);

int main(int argc, char *argv[])
{
char Array[SIZE], *Array_ptr = strtok(Array, " .");
StrInput(Array, SIZE);
int i=1, *temp = Array_ptr;

//Strok initialized in order to use NULL next sequence.
//Temp stores the pointer in it's original form, before it gets butchered by strtok
while (Array_ptr != NULL)
{
Array_ptr = strtok(NULL, " .");
i++;
}
//Above code finds the number of tokens strtok worked on, and stores it as i.

//Dynamically Creates the array which can hold exactly the amount of tokens (i)
int *Malloc_Array_ptr = (int*)malloc(i* sizeof(int)), hold;

i=0;
while (Array_ptr != NULL)
{
temp = strtok(NULL, " .");
hold = atoi(temp);
Malloc_Array_ptr[i] = hold;
i++;
}

printf("Show me the money: %s \n", Malloc_Array_ptr);
system("PAUSE");
return 0;
}


/*----------------------------------------------------------------------*/
void StrInput(char str[], int maxChars)
{
int i=0, str_lenght;
while ((str[i] = getchar()) != '\n')
i++;
str[i+1]='\0';


if (i>maxChars || i<MIN_SIZE)
{
printf("Your sumbition dosn't fit the size criteria.\n");
printf("Please reenter:\n\n");
StrInput(str, maxChars);
}
}

最佳答案

这是有问题的:

char Array[SIZE], *Array_ptr = strtok(Array, " .");

您正在声明数组,然后尝试在未初始化的数组上使用 strtok。您可能打算这样做:

char Array[SIZE], *Array_ptr = 0;
StrInput(Array, SIZE);
Array_ptr = strtok(Array, " .");

关于c - 将 char 数组中的信息放入动态创建的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16266472/

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