473,396 Members | 1,914 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

dynamic allocation array/function

Hi all,
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.

Here's what I have, but I get all kinds of errors.

help? :)

void getString (char str1 [], char str2 []) {

int length = 80;
char myStr [length];
cout << "Please enter a sentence: " << endl;
cin. getline (myStr, length);

int index = 0;
char *newArray;
newArray = new char [length];

while (myStr [index] != '\0') {
newArray [index] = myStr [index];
index ++;
}

newArray [index] = '\0';
}

Sep 23 '07 #1
3 4751
Sn*******@gmail.com wrote:
Hi all,
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.

Here's what I have, but I get all kinds of errors.

help? :)

void getString (char str1 [], char str2 []) {

int length = 80;
char myStr [length];
^^^^^^^^^^^^^^^^^^^^^^^^^^^

This type of allocation is non-standard. The number of elements needs
to be constant for "standard C++".

const int length( 80 );
char myStr [length];
cout << "Please enter a sentence: " << endl;
cin. getline (myStr, length);
I'm not sure if istrean::getline null terminates. You need to check.
>
int index = 0;
char *newArray;
newArray = new char [length];

while (myStr [index] != '\0') {
newArray [index] = myStr [index];
index ++;
}

newArray [index] = '\0';
The above is the same as strcpy no ?
}


All this is much easier with std::string of course.
Sep 24 '07 #2
On Sep 24, 12:52 am, Sneaky...@gmail.com wrote:
so i need to write a function called getString() that has a local char
array of 80 elements.
Why? That's about the most stupid requirement I can imagine.
In fact, almost by definition, a "requirement" doesn't specify
what is local to the function. (It might, possibly, specify
that the function cannot use more than N bytes of local
variables, if the target machine had a very limited stack.) And
I certainly wouldn't use such an array in real code.
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.
char*
getSentence()
{
std::string sentence ;
std::cout << "Input sentence: " ;
std::cin >sentence ;
char meetsRequirements[ 80 ] = {} ;
sentence.copy( meetsRequirements, 79 ) ;
char* result = new[ strlen( meetsRequirements )
+ 1 ] ;
strcpy( result, meetsRequirements ) ;
return result ;
}

It's all a bit stupid, though. I fail to see the point of it.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Sep 24 '07 #3
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--
Sep 24 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Scott Lyons | last post by:
Hey all, Can someone help me figure out how to pass a dynamic array into a function? Its been giving me some trouble, and my textbook of course doesnt cover the issue. Its probably something...
5
by: swarsa | last post by:
Hi All, I realize this is not a Palm OS development forum, however, even though my question is about a Palm C program I'm writing, I believe the topics are relevant here. This is because I...
13
by: jimjim | last post by:
Hello, I am coming from a C background and the below dynamic allocation of an array of pointers makes sense to me: #define SIZE 2 int **p; p = malloc ( SIZE * sizeof ( int * )); for(int j=0;...
13
by: xian_hong2046 | last post by:
Hello, I think dynamic memory allocation is supposed to be used when one doesn't know in advance how much memory to allocate until run time. An example from Thinking in C++ is to dynamically...
11
by: toton | last post by:
Hi, I have little confusion about static memory allocation & dynamic allocation for a cluss member. I have class like class Bar{ public: explicit Bar(){ cout<<"bar default"<<endl; }
24
by: Ken | last post by:
In C programming, I want to know in what situations we should use static memory allocation instead of dynamic memory allocation. My understanding is that static memory allocation like using array...
4
by: hobbes992 | last post by:
Howdy folks, I've been working on a c project, compiling using gcc, and I've reached a problem. The assignment requires creation of a two-level directory file system. No files have to be added or...
12
by: whitehatmiracle | last post by:
Hi all Im not quite sure how to use the new and delete for a whole array dynamically. Actually i want that, a user inputs a char in a single char array. Everytime he inputs a char he creates a...
1
by: Peterwkc | last post by:
Hello all expert, i have two program which make me desperate bu after i have noticed the forum, my future is become brightness back. By the way, my problem is like this i the first program was...
14
by: vivek | last post by:
i have some doubts on dynamic memory allocation and stacks and heaps where is the dynamic memory allocation used? in function calls there are some counters like "i" in the below function. Is...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.