【发布时间】:2015-03-05 20:13:36
【问题描述】:
这是一个简单的程序,我试图通过引用和字符串将结构传递给函数。该函数应该检测字符串的长度并将其分配给结构的成员。这是程序:
#include <iostream>
#include <string.h>
struct stringy // structure definition
{
char *str;
int ct;
};
void set(stringy &beany, const char *testing); // function definition
int main()
{
stringy beany;
char testing[] = "Reality isn't what it used to be.";
set(beany, testing); // function call
return 0;
}
void set(stringy &beany, const char *testing) // function prototype
{
int i=0;
while (*(testing+i) != '\0') // this loop counts the number of characters
{
i++;
std::cout << i << "\n";
}
beany.str = new char[i]; // dynamic storage allocation
std::cout << strlen(beany.str); // printing the length of the string
}
由于某种原因,函数 set() 的最后一行的输出是 47,而“i”的值是 33。最后 15 个字节被垃圾值填充。我希望beany.str的长度应该等于*testing的长度。
【问题讨论】:
标签: c++ function pointers structure