Sn*******@gmail.com writes:
so i need to write a function called getString() that has a local char
array of 80 elements. function should ask the user to enter a
sentence, and store the sentence in the array. then function should
dynamically allocate a char array just large enough to hold the
sentence, plus the null terminator. the function then will copy the
sentence to the dynamically allocated array, and return a pointer to
the array.
void getString (char str1 [], char str2 []) {
Your function returns nothing instead of desired pointer. What are
those arguments for? You probably meant:
char *getString() {
int length = 80;
As it was pointed already it needs to be "const int" or better skip it
char myStr [length];
and declare array as "char myStr[80];".
cout << "Please enter a sentence: " << endl;
cin. getline (myStr, length);
What if the line was more then 79 character long? What happens to the
rest of the line? You should ignore it or something.
int index = 0;
char *newArray;
newArray = new char [length];
while (myStr [index] != '\0') {
newArray [index] = myStr [index];
index ++;
}
newArray [index] = '\0';
Better use strcpy. Or since you should calculate string's length before
allocating memory you may even use memcpy (or C++ equivalent),
ie. replace code starting with "int index = 0;" with:
size_t num = strlen(myStr) + 1;
char *newArray = new char[num];
memcpy(newArray, myStr, num);
}
newArray is just thrown away. You are missing a "return newArray;"
before closing bracket.
Surly someone will kill me for this code but what the hell...
#v+
char *getString() {
char tmp[80], *ch;
puts("Please enter a sentence: ");
fgets(tmp, sizeof tmp, stdin);
for (ch = tmp; *ch && ch!='\n' ++ch);
if (!*ch) { /* Ignore the rest of the line */
for (int c; (c = getchar())!=EOF && c!='\n'; );
} else {
*ch = 0;
}
size_t num = ch - tmp + 1;
memcpy(ch = new char[num], tmp, num);
return ch;
}
#v-
--
Best regards, _ _
.o. | Liege of Serenly Enlightened Majesty of o' \,=./ `o
..o | Computer Science, Michal "mina86" Nazarewicz (o o)
ooo +--<mina86*tlen.pl>--<jid:mina86*jabber.org>--ooO--(_)--Ooo--