Click here to Skip to main content
15,880,608 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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
Posted

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 -
C#
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;
}
 
Share this answer
 
v2
Comments
[no name] 11-Mar-14 0:04am    
Correct but I had included it also.
«_Superman_» 11-Mar-14 1:09am    
I don't mean the usage of new and delete.
You can see the difference in how the myfunc function takes a reference to a char* and the syntactical differences because of that.
[no name] 11-Mar-14 1:12am    
Indeed and OP did mention c++.
Example using both malloc and new (commented out at present).

C++
#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 and free are used together as are new and delete. Using delete with malloc results in undefined behaviour.
 
Share this answer
 
v5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900