在本地函数中分配并初始化指针
我想分配内存并将其填充到指针,这是函数参数之一,但我认为我没有得到一些重要的东西,请帮助我。
所以,如果我这样做,一切都会正常:
void alloc(char **p, int n)
{
*p = new char[n];
}
int main() {
char * ptr = NULL;
int n = 10;
alloc(&ptr, n);
for(int i = 0; i<(n - 1); i++)
ptr[i] = '1';
ptr[n - 1] = '\0';
printf("%s", ptr);
return 0;
}
现在我想将分配的内存也初始化到
void alloc(char **p, int n)
{
*p = new char[n];
for(int i = 0; i<(n - 1); i++)
*p[i] = '1';
*p[n - 1] = '\0';
}
int main() {
char * ptr = NULL;
int n = 10;
alloc(&ptr, n);
printf("%s", ptr);
return 0;
}
程序崩溃函数中。我不明白为什么。请问有人可以解释一下吗?
I want to allocate memory and fill it to the pointer, that are one of the function parameter, but I think that I don't get some important thing, help me please.
So, If I do that everything works fine:
void alloc(char **p, int n)
{
*p = new char[n];
}
int main() {
char * ptr = NULL;
int n = 10;
alloc(&ptr, n);
for(int i = 0; i<(n - 1); i++)
ptr[i] = '1';
ptr[n - 1] = '\0';
printf("%s", ptr);
return 0;
}
Now I want to initialize the allocated memory also into the function
void alloc(char **p, int n)
{
*p = new char[n];
for(int i = 0; i<(n - 1); i++)
*p[i] = '1';
*p[n - 1] = '\0';
}
int main() {
char * ptr = NULL;
int n = 10;
alloc(&ptr, n);
printf("%s", ptr);
return 0;
}
Program crashes. I don't get why. Please, can someone explain?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
请尝试使用
(*p)[i]
和(*p)[n - 1]
。优先级规则导致*p[i]
被计算为*(p[i])
。Try
(*p)[i]
and(*p)[n - 1]
instead. The precedence rules cause*p[i]
to be evaluated as*(p[i])
.试试这个:
您的操作员评估顺序有问题。
Try this:
you have a problem with operator's evaluation order.
可能是因为这个:
被解释为好像你写了这个:
而不是好像你写了这个,这可能就是你的意思:
Probably because this:
is interpreted as if you had written this:
not as if you had written this, which is what you probably meant:
这应该可以解决问题,
如果您坚持使用指针作为参数,请更改
p
的 all在函数中
(*p)
(并且不要忘记检查空指针如果你通过了,就做一些合理的事情。
但是,考虑到所有因素,您最好使用
std::string
——这个函数甚至不是必需的,因为你可以写成
std::string( n, '1' )
。This should do the trick,
If you insist on using a pointer as argument, change all of the
p
in the function to
(*p)
(and don't forget to check for a null pointerand do something reasonable if you're passed one.
All things considered, however, you'd be better off using
std::string
—this function wouldn't even be necessary, as youcould write
std::string( n, '1' )
.试试这个
Try this
这是运营商优先级问题。在你的 alloc 函数中尝试一下:
Its a precedence of operators issue. Try this in your alloc function: