Returning an array -- help needed

A

Abhayks

Hi,
I am retuning to "C" after a long time and my basics are shatterred.
Not sure where I am making the mistake.
Please help.

#include<stdio.h>
#include<stdlib.h>

void foo( char ** ptr)
{
int i;
*ptr = malloc(255); // allocate some memory
// strcpy( *ptr, "Hello World");
for( i=0; i<5; i++)
{
*ptr='a';
}

}

int main()
{
char *ptr = 0;
// call function with a pointer to pointer
foo(&ptr );
printf("%s\n", ptr);
// free up the memory
free(ptr);
return 0;
}

Please advise why this is not working?
 
A

Abhayks

Abhayks said:
Hi,
I am retuning to "C" after a long time and my basics are shatterred.
Not sure where I am making the mistake.
Please help.
#include<stdio.h>
#include<stdlib.h>

void foo( char ** ptr)
{
  int i;
   *ptr = malloc(255); // allocate some memory
   // strcpy( *ptr, "Hello World");
   for( i=0; i<5; i++)
     {
       *ptr='a';
(*ptr)='a';

     }
(*ptr)=0;



int main()
{
    char *ptr = 0;
    // call function with a pointer to pointer
    foo(&ptr );
    printf("%s\n", ptr);
    // free up the memory
    free(ptr);
    return 0;
}

Please advise why this is not working?

1) Operator precedence. [] carries higher precedence than the unary *
operator.

2) The string must be zero-terminated. malloc does not clear allocated
memory.

 application_pgp-signature_part
< 1KViewDownload


God! how can I miss it.
I think 2 years of separation did the trick.
Thanks mate.
You really are a life saver.
 
V

Vidar Hasfjord

Abhayks writes:
[...]
Please advise why this is not working?
1) Operator precedence. [] carries higher precedence than the unary *
operator.
2) The string must be zero-terminated. malloc does not clear allocated
memory.

God! how can I miss it.

Maybe it would be just as well. There are better ways in C++ than
using pointers and manual memory handling. If you really did want to
return an array, as your subject title says, you can do it safely like
this:

typedef tr1::array <char, 255> Array;

Array foo () {
Array a = {'a', 'a', 'a', 'a', 'a'};
//strcpy (a.begin (), "Hello World");
return a;
}

int main () {
Array a = foo ();
cout << a.begin () << endl;
return 0;
}

But, of course, your example calls for std::string:

string foo () {
return "aaaaa"; // "Hello World";
}

int main () {
string s = foo ();
cout << s << endl;
return 0;
}

Regards,
Vidar Hasfjord
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top