how can I use data from array declared in a separate function 
Author Message
 how can I use data from array declared in a separate function

Here is my script, what I do is read a text file (Host file for
servers) in a function. The data is in the array "buff" (that works
fine), but when the function ends I get back in main() where I want to
use the gathered data in array "buff". I understand that I can't
return the data in "buff" to main() and that I have to use a pointer
from main() to get to the data. But I really have no clue how to
implement this into my script. Please help.

/* Declare variables*/
/* ========================================================================
*/
char HOSTFILE[] = "d:\\scripts\\lcc\\novellping\\novellhosts.txt";
enum {MAX_LEN = 10240};

/* Pull in all required C header files */
/* ========================================================================
*/
#include <stdio.h>

/* Declare function definitions */
/* ========================================================================
*/
void read_hostfile(FILE *fin);

/* =======================================================================
*/
/* MAIN */
/* =======================================================================
*/

int main() {

        FILE *fptr;
        if ((fptr = fopen(HOSTFILE, "r")) == NULL) {
                printf ("File %s cannot be opened for reading.\n", HOSTFILE);
        } else {
                printf ("Function \"read_hostfile()\" is now executed.\n");
                read_hostfile(fptr);
                printf ("\nBack to main().\n\n");
        }

        printf ("This is where I want to access the data in the array
\"buff\" from \"main()\".\n");

        printf ("\n\nEnd of main() program.\n");
        return 0;

Quote:
}

/* ========================================================================
*/
/* Function definitions */
/* ========================================================================
*/
/* Read all data from the HOSTFILE and put it in the array "buff" */
void read_hostfile(FILE *fin) {

        int num;
        char buff[MAX_LEN + 1];
        while (!feof(fin)) {
                num = fread(buff, sizeof(char), MAX_LEN, fin);
        }

        printf ("\n\n%s\n\n", buff);
        printf ("The enumerated size of array \"buff\" is: %i\n",
sizeof(buff));
        printf ("The real size of array \"buff\" is: %i\n", num *
sizeof(char));
        printf ("\n\nFile %s read and put in array \"buff\".\n", HOSTFILE);

Quote:
}

Thanx in advance,
Andre


Sat, 23 Jul 2005 19:52:22 GMT  
 how can I use data from array declared in a separate function

Quote:
> Here is my script, what I do is read a text file (Host file for
> servers) in a function. The data is in the array "buff" (that works
> fine), but when the function ends I get back in main() where I want to
> use the gathered data in array "buff". I understand that I can't
> return the data in "buff" to main() and that I have to use a pointer
> from main() to get to the data. But I really have no clue how to
> implement this into my script. Please help.
> /* Declare variables*/
> /* ========================================================================
> */
> char HOSTFILE[] = "d:\\scripts\\lcc\\novellping\\novellhosts.txt";
> enum {MAX_LEN = 10240};
> /* Pull in all required C header files */
> /* ========================================================================
> */
> #include <stdio.h>
> /* Declare function definitions */
> /* ========================================================================
> */
> void read_hostfile(FILE *fin);
> /* =======================================================================
> */
> /* MAIN */
> /* =======================================================================
> */
> int main() {

>    FILE *fptr;
>    if ((fptr = fopen(HOSTFILE, "r")) == NULL) {
>            printf ("File %s cannot be opened for reading.\n", HOSTFILE);
>    } else {
>            printf ("Function \"read_hostfile()\" is now executed.\n");
>            read_hostfile(fptr);
>            printf ("\nBack to main().\n\n");
>    }

>    printf ("This is where I want to access the data in the array
> \"buff\" from \"main()\".\n");

>    printf ("\n\nEnd of main() program.\n");
>    return 0;
> }
> /* ========================================================================
> */
> /* Function definitions */
> /* ========================================================================
> */
> /* Read all data from the HOSTFILE and put it in the array "buff" */
> void read_hostfile(FILE *fin) {

>    int num;
>    char buff[MAX_LEN + 1];
>    while (!feof(fin)) {
>            num = fread(buff, sizeof(char), MAX_LEN, fin);
>    }

>    printf ("\n\n%s\n\n", buff);
>    printf ("The enumerated size of array \"buff\" is: %i\n",
> sizeof(buff));
>    printf ("The real size of array \"buff\" is: %i\n", num *
> sizeof(char));
>    printf ("\n\nFile %s read and put in array \"buff\".\n", HOSTFILE);
> }

There are two possibilities: Either define 'buff' in main() and pass
the buffer to read_host() or define 'buff' in read_host() as static
and return the address of the buffer to main. I.e. either

void read_host( FILE *fin, char *buff );

int main( void )
{
    char buff[ MAX_LEN + 1 ];

    ....
    read_host( fptr, buff );
    ....

Quote:
}

void read_host( FILE *fin, char *buff )
{
    ....

Quote:
}

or

char *read_host( FILE *fin );

int main( void )
{
    char *buff_from_read_host;

    ...
    buff_from_read_host = read_host( fptr );
    ...

Quote:
}

char *read_host( FILE *fin )
{
    char buff[ MAX_LEN + 1 ];

    ....
    return buff;

Quote:
}

In the second case you have to be aware that calling read_host() a second
time will overwrite what has been written into buff during the first call,
so if main() still needs the information from the first invocation it has
to copy it into some additional buffer before calling read_host() again.

                                  Regards, Jens
--
      _  _____  _____

  _  | |  | |    | |
 | |_| |  | |    | |          http://www.physik.fu-berlin.de/~toerring
  \___/ens|_|homs|_|oerring



Sat, 23 Jul 2005 20:32:13 GMT  
 how can I use data from array declared in a separate function

Quote:
> Here is my script, what I do is read a text file (Host file for
> servers) in a function. The data is in the array "buff" (that works
> fine), but when the function ends I get back in main() where I want to
> use the gathered data in array "buff". I understand that I can't
> return the data in "buff" to main() and that I have to use a pointer
> from main() to get to the data. But I really have no clue how to
> implement this into my script. Please help.

Observe:

#include <stdio.h>
#include <string.h>

#define MAX_LEN 1024
int read_file(FILE *fp, char *buf, size_t len);

int main(void)
{
  char buffer[MAX_LEN] = {0};
  FILE *fp = fopen("hosts", "r");
  if(fp != NULL)
  {
    if(0 == read_file(fp, buffer, sizeof buffer))
    {
      printf("%s", buffer);
    }
    fclose(fp);
  }
  else
  {
    fprintf(stderr, "Can't open file.\n");
  }
  return 0;

Quote:
}

int read_file(FILE *fp, char *buf, size_t len)
{
  char *p = buf;
  char *last = NULL;
  size_t bytes = 0;
  size_t justread = 0;
  while(bytes < len && fgets(p, len - bytes, fp) != NULL)
  {
    last = strchr(p, '\n');
    if(last == NULL)
    {
      /* not enough room for the whole file */
      bytes = len;
    }
    else
    {
      justread = last + 1 - p;
      bytes += justread;
      p += justread;
    }
  }
  return ferror(fp);    

Quote:
}

--
Richard Heathfield (googling)


Sun, 24 Jul 2005 00:44:17 GMT  
 how can I use data from array declared in a separate function

Quote:
> /* Read all data from the HOSTFILE and put it in the array "buff" */
> void read_hostfile(FILE *fin) {

>    int num;
>    char buff[MAX_LEN + 1];
>       /* ... */
> }

In your function, your array's storage is on the stack.  It's
persistance is assured up until the function's execution is done.

Declare you array in a higher nesting level or allocate the array
dynamically.

I.e.,

char buffer[MAX_LEN + 1]; /* declared as a global or at an appropriate
nesting level */

void read_hostfile(FILE *fin, char * buff )
{
        int num;
        while (!feof(fin)) {
                num = fread(buff, sizeof(char), MAX_LEN, fin);
        }

       /* ... */

Quote:
}

--------
*** Or you can allocate dynamically inside the function:
--------

void read_hostfile(FILE *fin)
{
        int num;
        char * buff = (char*) malloc( MAX_LEN + 1 );

        if (buff != NULL)
        {
            while (!feof(fin)) {
                    num = fread(buff, sizeof(char), MAX_LEN, fin);
            }
            /* ... */
        }
        else
        {
            printf("malloc(%d) has failed", MAX_LEN + 1);
        }

Quote:
}

Btw, sorry if there's too much source code in the answer...


Sun, 24 Jul 2005 01:56:46 GMT  
 how can I use data from array declared in a separate function

I made a mistake on my dynamic allocation solution... dont' forget to
return the pointer...

char * read_hostfile(FILE* fin) {
        int num;
        char * = (char*)malloc(MAX_LEN + 1);

        if (!buff)
            return NULL;

        while (!feof(fin)) {
                num = fread(buff, sizeof(char), MAX_LEN, fin);
        }

        /* ... printfs... */

        /* return the pointer to the newly allocated memory to caller
*/
        return buff;    

Quote:
}

(how many people will be peeling me out before this gets posted...
only time will tell)


Sun, 24 Jul 2005 02:07:29 GMT  
 how can I use data from array declared in a separate function

Quote:

> char *read_host( FILE *fin );

> int main( void )
> {
>     char *buff_from_read_host;

>     ...
>     buff_from_read_host = read_host( fptr );
>     ...
> }

> char *read_host( FILE *fin )
> {
>     char buff[ MAX_LEN + 1 ];

>     ....
>     return buff;
> }

Don't forget the 'static':

Quote:
> char *read_host( FILE *fin )
> {
>     static char buff[ MAX_LEN + 1 ];

>     ....
>     return buff;
> }

-- L.L.


Sun, 24 Jul 2005 02:59:16 GMT  
 how can I use data from array declared in a separate function

Quote:


> > Here is my script, what I do is read a text file (Host file for
> > servers) in a function. The data is in the array "buff" (that works
> > fine), but when the function ends I get back in main() where I want to
> > use the gathered data in array "buff". I understand that I can't
> > return the data in "buff" to main() and that I have to use a pointer
> > from main() to get to the data. But I really have no clue how to
> > implement this into my script. Please help.

> > /* Declare variables*/
> > /* ========================================================================
> > */
> > char HOSTFILE[] = "d:\\scripts\\lcc\\novellping\\novellhosts.txt";
> > enum {MAX_LEN = 10240};

> > /* Pull in all required C header files */
> > /* ========================================================================
> > */
> > #include <stdio.h>

> > /* Declare function definitions */
> > /* ========================================================================
> > */
> > void read_hostfile(FILE *fin);

> > /* =======================================================================
> > */
> > /* MAIN */
> > /* =======================================================================
> > */

> > int main() {

> >       FILE *fptr;
> >       if ((fptr = fopen(HOSTFILE, "r")) == NULL) {
> >               printf ("File %s cannot be opened for reading.\n", HOSTFILE);
> >       } else {
> >               printf ("Function \"read_hostfile()\" is now executed.\n");
> >               read_hostfile(fptr);
> >               printf ("\nBack to main().\n\n");
> >       }

> >       printf ("This is where I want to access the data in the array
> > \"buff\" from \"main()\".\n");

> >       printf ("\n\nEnd of main() program.\n");
> >       return 0;
> > }

> > /* ========================================================================
> > */
> > /* Function definitions */
> > /* ========================================================================
> > */
> > /* Read all data from the HOSTFILE and put it in the array "buff" */
> > void read_hostfile(FILE *fin) {

> >       int num;
> >       char buff[MAX_LEN + 1];
> >       while (!feof(fin)) {
> >               num = fread(buff, sizeof(char), MAX_LEN, fin);
> >       }

> >       printf ("\n\n%s\n\n", buff);
> >       printf ("The enumerated size of array \"buff\" is: %i\n",
> > sizeof(buff));
> >       printf ("The real size of array \"buff\" is: %i\n", num *
> > sizeof(char));
> >       printf ("\n\nFile %s read and put in array \"buff\".\n", HOSTFILE);
> > }

> There are two possibilities: Either define 'buff' in main() and pass
> the buffer to read_host() or define 'buff' in read_host() as static
> and return the address of the buffer to main. I.e. either

> void read_host( FILE *fin, char *buff );

> int main( void )
> {
>     char buff[ MAX_LEN + 1 ];

>     ....
>     read_host( fptr, buff );
>     ....
> }

> void read_host( FILE *fin, char *buff )
> {
>     ....
> }

> or

> char *read_host( FILE *fin );

> int main( void )
> {
>     char *buff_from_read_host;

>     ...
>     buff_from_read_host = read_host( fptr );
>     ...
> }

> char *read_host( FILE *fin )
> {
>     char buff[ MAX_LEN + 1 ];

>     ....
>     return buff;
> }

> In the second case you have to be aware that calling read_host() a second
> time will overwrite what has been written into buff during the first call,
> so if main() still needs the information from the first invocation it has
> to copy it into some additional buffer before calling read_host() again.

>                                   Regards, Jens

Thankx for posting this solution Jens.
I got it working with the first one :-)

The second one, I ran into a compilation error:

Warning novellping.c: 110  pointer to local `buff' is an illegal
return value
0 errors, 1 warnings

Line 110 is:

return buff;

So if you can explain to me what went wrong there I would be very
pleased, than I can use them both.

Thanx in advance,
Andre



Sun, 24 Jul 2005 04:21:01 GMT  
 how can I use data from array declared in a separate function

Quote:

>> There are two possibilities: Either define 'buff' in main() and pass
>> the buffer to read_host() or define 'buff' in read_host() as static
>> and return the address of the buffer to main. I.e. either

<snipped>

Quote:
>> char *read_host( FILE *fin )
>> {
>>     char buff[ MAX_LEN + 1 ];

>>     ....
>>     return buff;
>> }

>> In the second case you have to be aware that calling read_host() a second
>> time will overwrite what has been written into buff during the first call,
>> so if main() still needs the information from the first invocation it has
>> to copy it into some additional buffer before calling read_host() again.
> The second one, I ran into a compilation error:
> Warning novellping.c: 110  pointer to local `buff' is an illegal
> return value
> 0 errors, 1 warnings

As Louis Lesage already wrote in a reply I made a stupid mistake here:
while I mentioned in the text that buff in read_host() must be declared
as static (so the memory associated with it does not get lost on leaving
the function) I forgot to put it into the example function. I.e. you
need

char *read_host( FILE *fin )
{
    static char buff[ MAX_LEN + 1 ];
  /*^^^^^^*/
    ....
    return buff;

Quote:
}

Without "static" returning the address of buff is of course illegal
(or at least very stupid) because buff goes out of scope when the
function is left and what gets returned can't be used for anything.
Sorry for the confusion.
                                  Regards, Jens

PS.: You may also try the third method Louis Lesage proposed, i.e.
     using dynamic allocation, even though I would write it slightly
     different:

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

char *read_host( File *fin )
{
    char *buff;

    if ( ( buff = malloc( MAX_LEN + 1 ) ) == NULL )
    {
        fprintf( stderr, "Can't allocate memory.\n" );
        exit( EXIT_FAILURE );
    }

    ...

    return buff;

Quote:
}

Please note that in this case the calling function is responsible for
calling free() on the pointer it got from read_host() when the buffer
isn't needed anymore. The advantage compared to the version where you
use static memory is that you can call the function as man times as
you like and always get a new buffer, so the calling function does not
have to make a copy before calling read_host() again in case it still
needs the results from a previous call.

Keeping my fingers crossed I didn't made another mistake here....
--
      _  _____  _____

  _  | |  | |    | |
 | |_| |  | |    | |          http://www.physik.fu-berlin.de/~toerring
  \___/ens|_|homs|_|oerring



Sun, 24 Jul 2005 07:23:27 GMT  
 
 [ 8 post ] 

 Relevant Pages 

1. Declaring an array of pointers in Visual Basic (and putting and getting data from it)

2. Using data types before they are declared.

3. Declaring function with array parameter

4. Declaring array of constant characters (using [])

5. declaring an array of function pointers?

6. how to declare arrays of functions?

7. declaring and array of function*

8. Beginner [Q] Using Canned File Open/Save dialog

9. How to declare byte array in struct used for interop

10. declaring an array of pointers to malloced arrays

11. declaring functions inside other functions

12. Using values of one array as pointer counters to access data in another ( long )

 

 
Powered by phpBB® Forum Software