C++ C++;合并两个以零结尾的字符串?
所以我在做一个问题,我必须连接两个以零结尾的字符串,第一个包含一个单词,第二个是空的,大小是原始数组的两倍。我能够使用下面的代码使它工作C++ C++;合并两个以零结尾的字符串?,c++,pointers,c-strings,C++,Pointers,C Strings,所以我在做一个问题,我必须连接两个以零结尾的字符串,第一个包含一个单词,第二个是空的,大小是原始数组的两倍。我能够使用下面的代码使它工作 #include <stdio.h> #include <iostream> using namespace std; int main() { char str1[] = "test"; char str2[(sizeof(str1)-1)*2]; char *p; int co
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
char str1[] = "test";
char str2[(sizeof(str1)-1)*2];
char *p;
int count = 0;
for(p = str1; *p != 0; p++) {
str2[count] = *p;
count++;
}
cout << str2;
}
所以我试过这个
#include <stdio.h>
#include <iostream>
using namespace std;
char *copy_and_reverse(char *a) {
char str2[8];
int count = 0;
char* b = str2;
for(a; *a != 0; a++) {
str2[count] = *a;
count++;
}
return b;
}
int main()
{
char str1[] = "test";
char *a;
a = str1;
char* b = copy_and_reverse(a);
for(b; *b != 0; b++) {
cout << *b;
}
}
注意:不应使用任何库函数(例如从string.h
)
我相信这将满足您的需要:
#include <stdio.h>
#include <stdlib.h>
static char* copy_and_reverse(char* a);
static int strlen(char *c); // self-implemented
int main(void) {
char *a = "some string";
char *b = copy_and_reverse(a);
printf("%s", b);
free(b);
return 0;
}
static char* copy_and_reverse(char* a) {
int n = strlen(a);
char *b = new char[n * 2 + 1]; // get twice the length of a and one more for \0
for (int i = 0; i < n; ++i) { // does copying and reversing
b[i] = a[i];
b[i+n] = a[n-i-1];
}
b[2 * n] = '\0'; // null out last one
return b;
}
static int strlen(char *c) {
char *s = c;
while( *s++ );
return s-c-1;
}
#包括
#包括
静态字符*复制和反转(字符*a);
静态整数strlen(char*c);//自我实现
内部主(空){
char*a=“一些字符串”;
char*b=复制和反转(a);
printf(“%s”,b);
免费(b);
返回0;
}
静态字符*复制和反转(字符*a){
int n=strlen(a);
char*b=new char[n*2+1];//获取两倍于a的长度和一倍于\0的长度
对于(int i=0;i
在您的复制和反向
代码中有两个大问题
str2
不是有效字符串。修正:
str2[count] = '\0'; // after the loop
copy\u and\u reverse
返回指向局部变量(str2
)的指针。函数返回后,它的所有局部变量都消失了,main
正在处理一个无效指针。要解决此问题,请使用静态内存(例如,通过将str2
声明为static
或使其成为全局变量)或动态内存(使用new[]
(或malloc()
)分配存储)。这两种方法都有其缺点
,(b;…))变量代码>不执行任何操作(请参见(a;…)
对于最终结果来说不够大str2
有5个字节长(str1
),因此't','e','s','t','0'
现在就足够了,但最后您需要为结果分配char str2[8]
字节长度*2+1
合并
(不清楚这应该做什么),最后一个示例包含复制和反向
(其中没有反向)。你说你在做一个问题。练习的实际文本是什么?除了char*
进行学习。如果你使用C++,并不意味着你不需要知道引擎盖下的工作原理。@ HOLYBLASCATE是的,你不能使用OPEXTHORE。反向PLSITS甚至不编译。不要在C++中使用C样式的cj.@ MelpOMeNE编译:但是,为什么使用<代码> MalOC 这里代替了代码>新< /代码>?
#include <stdio.h>
#include <stdlib.h>
static char* copy_and_reverse(char* a);
static int strlen(char *c); // self-implemented
int main(void) {
char *a = "some string";
char *b = copy_and_reverse(a);
printf("%s", b);
free(b);
return 0;
}
static char* copy_and_reverse(char* a) {
int n = strlen(a);
char *b = new char[n * 2 + 1]; // get twice the length of a and one more for \0
for (int i = 0; i < n; ++i) { // does copying and reversing
b[i] = a[i];
b[i+n] = a[n-i-1];
}
b[2 * n] = '\0'; // null out last one
return b;
}
static int strlen(char *c) {
char *s = c;
while( *s++ );
return s-c-1;
}
str2[count] = '\0'; // after the loop