[英]String concatenation query c++
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <iostream>
using namespace std;
char a[21]; // If this is put inside the function unter -> junk output
char* b="";
void unter()
{
char *new_str = "";
strcpy(a, new_str);
char str_temp[10]="";
int chnum =0, neighbor1=3, neighbor2=5, mynode=4;
sprintf(str_temp,"%d",chnum);
b = strcat(a, str_temp);
b = strcat(b, "_from");
sprintf(str_temp,"%d",mynode);
b = strcat(b, str_temp);
b = strcat(b, "to");
sprintf(str_temp,"%d",neighbor1);
b = strcat(b, str_temp);
}
int main()
{
unter();
cout << a;
cout << b;
std::cin.get();
}
This is my code in C++. 这是我在C ++中的代码。 I'm not sure how the character array 'a' also has the same values as 'b'. 我不确定字符数组“ a”是否也具有与“ b”相同的值。 And moreover, when I declare 'a' 而且,当我声明“ a”时
char a[21];
inside function unter(), I'm getting some junk value for 'b'(as output). 在函数unter()中,我得到了'b'的一些垃圾值(作为输出)。 Care to explain how? 关心解释如何?
b = strcat(a, str_temp);
可能是造成问题的原因,因为strcat()的返回值是传递给它的第一个参数,因此为什么看到a
和b
相等,因为在该调用中b
设置为a
。
a
is a char array and b
is a pointer that points to a
, so when printing them, they always print the same thing. a
是char数组和b
是一个指向指针a
,所以打印时他们,他们总是打印同样的事情。 When you move the declaration for a
into unter
, it is destroyed when unter
returns, leaving b
a dnagling pointer, so you get garbage when you print it. 当您移动的声明a
成unter
,它被摧毁时, unter
的回报,让b
等你拿垃圾当你打印一个dnagling指针。
strcat() returns the result of the concatenation operation, so strcat()返回串联操作的结果,因此
b = strcat(a, str_temp);
results in b pointing to the array a[]. 导致b指向数组a []。 The subsequent strcat() operations effectively do the same, so the end result is that b points to a[] as you observe. 随后的strcat()操作有效地执行了相同的操作,因此最终结果是,正如您观察到的那样,b指向a []。 If you declare a[] inside unter() it will have local scope to that function, with the result that the global variable b will point to random/undefined memory contents after you exit the call to unter(). 如果在unter()中声明a [],它将对该函数具有局部作用域,结果是,在退出对unter()的调用后,全局变量b将指向随机/未定义的内存内容。
It's mildly worth noting that you're doing a lot of work that could be accomplished more easily with 值得一提的是,您正在做很多工作,而这些工作可以更轻松地完成
sprintf(a, "%d_from%dto%d", chnum, mynode, neighbor1);
You can do the whole concatenation and sprintf's in a single line. 您可以在一行中完成整个串联和sprintf的操作。
char* b="";
void unter()
{
int chnum =0, neighbor1=3, neighbor2=5, mynode=4;
char str_temp[21];
sprintf(str_temp,"%d_from%dto%d", chnum, mynode, neighbor1);
b = new char[strlen(str_temp)+1];
b = strcpy(b, str_temp);
}
Only funny thing is you must remember to delete b when you are done. 唯一可笑的是,您必须记得在完成操作后删除b。 The other option is using the a buffer and sprintf directly to it: 另一个选择是使用a缓冲区并将sprintf直接用于它:
char a[21];
void unter()
{
int chnum =0, neighbor1=3, neighbor2=5, mynode=4;
char str_temp[21];
sprintf(a,"%d_from%dto%d", chnum, mynode, neighbor1);
}
In addition to the other hints provided, you should take notice of the line 除了提供的其他提示之外,您还应该注意该行
b = strcat(b, str_temp);
which seems rather inappropriate for b is merely defined as a char pointer to a single byte storage ("" defines an empty string, ie an array of chars with a single element containing '\\0') 对于b来说似乎不合适,只是将其定义为指向单个字节存储的char指针(“”定义了一个空字符串,即,一个char数组,其中单个元素包含“ \\ 0”)
So when strcat appends to b, it creates a buffer overrun. 因此,当strcat追加到b时,它将创建缓冲区溢出。
Edit :Actually I just noticed that b was assigned to point to a, (thanks to the line preceding the one mentionned) so that would then be ok, since a may have the room for this... It doesn't make sense however, to need the two variables. 编辑 :实际上,我只是注意到b被分配为指向a,(这要归功于前面提到的那一行),这样就可以了,因为a可能有余地...但是这没有任何意义。 ,需要两个变量。
Maybe what you do not understand, is that although strcat() returns a pointer, this return doesn't need to be "consumed", it is merely a convenience, for when we chain commands an such. 也许您不了解的是,尽管strcat()返回了一个指针,但是不需要“消耗”该返回,这只是一种方便,因为当我们链接这样的命令时。 In other words you can simply write: 换句话说,您可以简单地编写:
strcat(a, str_temp);
Not requiring any char * b. 不需要任何字符* b。
When you define a
inside the function, memory for the variable a
is allocated on stack. 当您在函数内部定义a
变量时,变量a
内存将在堆栈中分配。 This memory is destroyed when the function exits. 函数退出时,该内存将被破坏。 Your pointer b
is pointing to starting address of a
. 您的指针b
指向开始的地址a
。 Now, if you try to access b
outside the function, it is pointing to a memory location which is already destructed and contain garbage values. 现在,如果您尝试访问该函数之外的b
,则它指向已被破坏并包含垃圾值的内存位置。 Basically, b
becomes a dangling pointer. 基本上, b
变为悬空指针。
If you declare a
inside the unter()
function, then it is only scoped inside that function. 如果在unter()
函数内部声明a
内部,则仅在该函数内部作用域。 Attempt to print b
from outside the function will print junk since it is pointing to a
which is already destroyed. 尝试打印b
从功能之外将打印垃圾,因为它指向a
这是已经被破坏。
This is a classic example of why you should always make sure to not to point to a local variable from a global one. 这是一个经典示例,说明了为什么您应始终确保不要从全局变量中指向局部变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.