【发布时间】:2019-01-19 21:12:23
【问题描述】:
已解决
我创建一个新的char *ch malloc(strlen) 并逐个字符地循环该字符串。然后我使用memcpy(ch, &stringpool[index], len) 将其复制回来当然,之后free(ch)。
我希望我的问题的标题是正确的。
我有一个字符串池
char **string_pool;
在类似的函数中启动
string_pool = malloc( sizeof(char *) * 1024);
我从标准输入获取字符串并将它们扫描到数组中
scanf("%[^\n]s", &string_pool[index]);
所以我可以使用 printf 打印出来
printf("gets %s\n", &string_pool[index]);
我该怎么做
- 获取string_pool[index]的长度
- 在循环中逐个字符读取 string_pool[index] 字符
谢谢
编辑
也许我应该多解释一下,它是一个带有虚拟指令集和类似程序的虚拟机
push 1
read
gets
应该:
- 将 1 压入堆栈 -> 让 x 为 1
- 将标准输入作为字符串读入 string_pool[x]
- 将所有字符压入堆栈
函数看起来像
case GETS: {
int index = popv(); // index is already on top of the stack
int strl = strlen(&string_pool[index]);
printf("gets %s with a length of %d\n", &string_pool[index], strl);
// pseudo code
// push each char as integer on the stack
foreach(char in string_pool[index]) push((int)char);
break;
}
case READ: {
int index = popv();
scanf("%[^\n]s", &string_pool[index]);
break;
}
case WRITE: {
int index = popv();
printf("%s", &string_pool[index]);
break;
}
我的问题是在GETS 案例中。我想将每个 char 作为 int 推入堆栈。
【问题讨论】:
-
使用
strlen()有什么问题? -
当我使用 strlen(&string_pool[i]) 我得到一个编译器错误
expected 'const char *' but argument is of type 'char **' -
scanf("%[^\n]s", string_pool[index]);将导致未定义的行为,因为您没有为 string_pool[index] 分配任何空间。 -
请出示 MCVE (minimal reproducible example)。目前尚不清楚您的编辑要做什么。
-
您的实际问题是什么?你有什么问题?标题是一个指令,而不是一个问题。