Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem with array as return value 1

Status
Not open for further replies.

obliik

Programmer
Dec 1, 2002
2
US
I'd be extremely grateful if someone could tell me why I get runtime errors with the following code. I want to pass the array inBuf[6] containing the characters {HELLO} to the function getAbbrv() and return only the first 3 characters in an array. If I pass HELLO, I want the return array abb[] to contain HEL. How do I do this?
Thanks a million!
KH.
--------------------------------------------

#include <cstring>
#include <stdlib.h>
#include <ostream.h>

void getAbbrv( char* inbuf, char abb[])
{
char ab[3];
for (int i = 0; i < 2; i++)
{
ab = inbuf;
}
ab = '\0';
strcpy(abb, ab);
//cout << &quot;ABB IS---&quot;<< abb << endl;
}

int main()
{

char inBuf[] = &quot;HELLO&quot;;
char* abbrv = &quot;XX&quot;;


/* this for loop is just to test my inBuf array */
for (int i = 0; i<strlen(inBuf)+1; i++)
cout << inBuf;
cout << '\n' ;

/* this is the function call that doesn't work */
getAbbrv( inBuf, abbrv);
return 0;
}
 
Could you repost the code with &quot;Process TGML&quot; switched off? It is difficult to figure out where appears in the code.

At a guess, if you wish to return a 3 letter abbreviation, unless you are using C99, you have to allocate a 4 character array. MSC is based on C89 and would expect a 4 character array, so ab should be declared as ab[4].

In main, allocate an array instead of initializing it to a const string i.e. char abbrv[4].
 
Why not something like this :

main()
{
char inbuff[]=&quot;HELLO&quot;;
char abb[4]; // Allow extra byte for NULL terminator

.
.
getabbrev(inbuff,abb);
.
.
}

void getabbrev(char * inbuff, char * abb)
{
strncpy(abb,inbuff,3);
abb[3]=0x00;
return;
}

Cheers
 
Or like this..simpler???
void getabbrev(char * inbuff, char * abb)
{
abb=new char(strlen(inbuff));
strncpy(abb,inbuff,3);
abb[3]=NULL;
return;
}
 
Thanks for the replies, guys. Newmankj's code worked. I spent several hours trying to figure this out myself.
obliik
 
The only problem I have with pankajkumar's code is that he allocates memory within the getabbrev function but never frees it, unless the memory is freed elsewhere a memory leak will result. Also there is a waste of memory in that abb is allocated as being the length of the input string when only 4 bytes are required.

Perhaps it would be better for the allocation of the abbreviation buffer to be left up to the caller, this way the caller can then also be responsible for freeing the memory when no longer required.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top