[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: malloc




Jordan Bettis said:
> If I needed to malloc a chunck of memory in one source file, change it,
> then use the data in another source file, could I just extern the pointer
> to the memory in a header file and include it [the header] in both files?

Uh, you mean in a global variable?  Sure, but is there any particular
reason you just can't pass the pointer around?  Something like this:

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

    void walk_all_over(char *, int);

    int main(int argc, char **argv)
    {
	char *foo;

	/* malloc() 1k */
	if (((void *)foo=malloc(1024))==NULL)
	{
	    perror("malloc() failed");
	    exit(EXIT_FAILURE);
	}

	/* write a bunch of a's to it */
	walk_all_over(foo, 1024);

	printf("%s\n", foo);

	return 0;
    }

    void walk_all_over(char *foo, int size)
    {
	int n;

	for (n=0;n<size;n++)
	{
	    *(foo+n)='a';
	}
    }

The walk_all_over() function doesn't know anything about any of the
variables in main(), there are no globals, and everything works
beautifully (and will work even if walk_all_over() is in another
source file).

Steve
-- 
steve@silug.org           | Linux Users of Central Illinois
(618)398-7320             | Meetings the 4th Tuesday of every month
Steven Pritchard          | http://www.luci.org/ for more info

--
To unsubscribe, send email to majordomo@luci.org with
"unsubscribe luci-discuss" in the body.