指向字符串变量的指针的问题 [英] Question on pointer to string variable
问题描述
Hello Guys,
我有一个关于c launguage编程的问题。 (也适用于c ++)
问题:在主要的,我有一个指向字符串变量的指针,让我们说char * p。我从main调用函数func1()。我想做以下。
1)在func1()内部,我想使用malloc方法为p分配20个字节,后来我想将Hello word复制到字符串变量中。
2)函数调用(func1())之后,我想打印p变量中的值。
我该怎么做?
问候,
Joy
Hello Guys,
I have one question on programming in c launguage. ( valid for c++ as well)
Question: In the main, I have a pointer to string variable, lets say char *p . I am calling a function func1() from main.I am would like to do following.
1) Inside func1(), I would like to assign 20 bytes to p using malloc method and later I would like to copy "Hello word " in to the string variable.
2) After function call ( func1()), I would like to print value that is in p variable.
How can I do this?
Regards,
Joy
推荐答案
pwasser [ ^ ]完美地回答了你的问题。
只是为了加入它,因为你也提到了C ++。
在C ++中,你可以也用更清晰的语法做到这一点 -
pwasser[^] has answered your question perfectly.
Just to add to it since you also mentioned C++.
In C++, you could also do this with a cleaner syntax -
int myfunc(char*& p)
{
p = new char[20];
strcpy(p, "Hello world");
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
char* mypointer = NULL;
myfunc(mypointer);
cout << mypointer << endl;
delete [] mypointer;
return 0;
}
使用malloc和new的示例(目前已注释掉)。
Example using both malloc and new (commented out at present).
#include "stdafx.h"
#include <iostream>
using namespace std;
int myfunc(char **p)
{
//*p = new char[20];
*p = (char*) malloc (20);
strcpy(*p, "Hello world");
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
char * mypointer = NULL;
myfunc( &mypointer);
cout << mypointer << endl;
// delete [] mypointer;
free(mypointer);
return 0;
}
malloc和free一起使用,新增和删除。对malloc使用delete会导致未定义的行为。
malloc and free are used together as are new and delete. Using delete with malloc results in undefined behaviour.
这篇关于指向字符串变量的指针的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!