I have main function like this:
void main()
{
char *s;
inputString(s);
printf("%s",s);
}
and inputString function:
void inputString(char *&s)
{
//Some code line to input a string and set s point to this string
}
Is there ha开发者_如何学Gove a function auto malloc memory enough store string which inputed (I need input string in inputString function).
Just 3 lines of code (put these inside int main()
)are enough
std::string s;
std::cin >> s; //or getline() as desired
std::cout << s;
If you keep using this C style approach, then no, you will have to make assumptions and allocate enough memory yourself. The C++ approach is much more superior, use std::strings and don't do manual allocations:
#include <string>
#include <iostream>
void inputString(std::string& s)
{
//Don't bother for the memory management
}
int main()
{
std::string s;
inputString(s);
std::cout << s ;
}
Also do note that your code is not legal C++. void main()
is illegal!!!
Edit: At the time of this answer the question was tagged C++. Later the question was retagged NOT by the OP, and I don't quite agree with it...
You're mixing C and C++ in your example.
In your case before you can use s it should be initialized. For example, like this:
void inputString(char *&s)
{
s = strdup(xxx); // or malloc, calloc, etc.
}
But really, then it's better to just use plain old C:
char* inputString(void)
{
char* s = strdup(xxx);
return s;
}
Assuming that you are doing this is C and not C++.
There are two approaches, either inputString
must allocate the memory or the caller of inputString
must allocate the memory.
if inputString allocates the memory your function will probably look something like:
char* inputString(void)
{
int len = strlen (MyInternalString) + 1;
char* s = malloc (len);
strncpy(s, MyInternalString, len);
return s;
} //similar to what Rustram illustrated
you should also include: void freeString(char* str) { free(str); } as well. This makes it clear to the user that they are required to manage the memory of the returned string themselves.
Alternatively you can write inputString where the user is expected to provide the required memory. This will then look something like
int inputString(char* str, int maxLen) //
{
if (maxLen >= myInternalStringLength + 1)
{
strncpy(str, myInternalString, maxLen)
}
return myInternalStringLength + 1;
}
Here the user of my string can check the return code to see if the buffer that he allocated was big enough. If it was too small, then he can always realloc a bigger one
Your main now becomes:
int main()
{
char *s = NULL;
int len = inputString(s, 0);
s = alloca(len); //allocates the memory on the stack
len = inputstring(s, len);
printf("%s",s);
} //no need to free the memory because the memory alloca'ed gets
//freed at the end of the stack frame
int main()
{
std::string s;
inputString(s);
printf("%s",s.c_str());
}
and inputString function:
void inputString(std::string& s)
{
//Some code line to input a string and set s point to this string
std::cin >> s;
}
精彩评论