En supposant que vous faites cela est C et non C++.
Il existe deux approches, soit inputString
doit allouer la mémoire ou l'appelant de inputString
doit allouer la mémoire.
si inputString alloue la mémoire de votre fonction sera probablement quelque chose comme:
char* inputString(void)
{
int len = strlen (MyInternalString) + 1;
char* s = malloc (len);
strncpy(s, MyInternalString, len);
return s;
} //similar to what Rustram illustrated
vous devez également inclure: freeString void (char * str) { libre (str); } également. Ceci indique clairement à l'utilisateur qu'il doit gérer lui-même la mémoire de la chaîne renvoyée.
Vous pouvez également écrire inputString où l'utilisateur doit fournir la mémoire requise. Cela ressemblera à ça
int inputString(char* str, int maxLen) //
{
if (maxLen >= myInternalStringLength + 1)
{
strncpy(str, myInternalString, maxLen)
}
return myInternalStringLength + 1;
}
Ici, l'utilisateur de ma chaîne peut vérifier le code de retour pour voir si le tampon qu'il a alloué était assez grand.Si elle était trop petite, alors il peut toujours réallouer un plus grand
Votre principal devient maintenant:
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
est ce C ou C++? –
Quel est le problème en utilisant 'std :: string' et' std :: cin'? –
est cet anglais? – Simone