这是我的代码
int main(int argc, char *argv[]) {
char const *strings[10] = {"dhh", "aci", "cdh"};
join_def(strings, 'l');
return EXIT_SUCCESS;
}
// part 1 read lines
void join_def(char const **strings, char delim) {
char *t = new char[100];
//int length = 0;
t[0] = '\0';
int x = sizeof(strings);
std::cout << delim << std::endl;
for (int i = 0; i < x; i++) {
int size = 0;
while(strings[i][size]!='\0'){
size++;
std::cout << strings[i][size] << std::endl;
}
}
}
我已经花了几个小时,只是无法连接它。对于此任务,我不能使用cstring或iostream以外的任何东西,所以请不要提出建议。
输出必须是c字符串=“ dhhlacilcdh”
首先,您无法确定传递给函数的数组中的元素数量,因为该数组将衰减为简单的指针。因此,您的sizeof(strings)
表达式将(在编译时)计算为指针的(固定)大小(以字节为单位)。为了使函数“知道”数组中有多少个元素,需要明确地告诉它(通过额外的参数)。
其次,您的i
'和size
索引std::cout << strings[i][size] << std::endl;
在行中的索引方式错误,并且进一步地,您size
在打印相关字符之前先进行了递增,而在打印完相关字符后应进行递增。
下面的代码还对字符串进行了实际的串联,修改后的join_def
函数现在返回一个指向该结果的指针(完成后必须将其释放)。
#include <iostream>
char* join_def(char const** strings, char delim, int x)
{
char* t = new char[100];
int length = 0;
t[0] = '\0';
//int x = sizeof(strings);
std::cout << delim << std::endl;
for (int i = 0; i < x; i++) {
int size = 0;
while (strings[i][size] != '\0') {
std::cout << strings[i][size] << std::endl;
t[length++] = strings[i][size]; // Append this character
size++;
}
t[length++] = delim; // Append delimiter
}
t[length] = '\0'; // Append nul-terminator
return t;
}
int main()
{
char const* strings[10] = { "dhh", "aci", "cdh" };
char* result = join_def(strings, 'l', 3);
std::cout << result << std::endl;
free(result);
return 0;
}
还要注意,我已经将join_def
功能代码移到了main
(称为)之前。如果您不这样做,那么至少必须在main之前提供该函数的(正向)声明(仅靠achar* join_def(char const** strings, char delim, int x);
本身就可以)。
随时要求进一步的澄清和/或解释。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句