LinuxQuestions.org
Visit Jeremy's Blog.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 02-08-2012, 02:43 AM   #1
akshay_satish
Member
 
Registered: May 2011
Posts: 63

Rep: Reputation: Disabled
pointer concept


Hi I have a global character pointer say.,
char *p = 0;
char *q = 0;

I got two functions a() & b();

<CODE>
static int a()
{
p = malloc(10);

someMethod(p, q);
}

static int b()
{
q = malloc(10);

someMethod(p, q);
}
</CODE>
The above snippet will work considering p & q as global pointer. Is there any way I can use p & q as local between a() & b()?
 
Old 02-08-2012, 03:59 AM   #2
Ramurd
Member
 
Registered: Mar 2009
Location: Rotterdam, the Netherlands
Distribution: Slackwarelinux
Posts: 703

Rep: Reputation: 111Reputation: 111
you can pass your pointers as arguments to your functions

Code:
int main(int argc, char *argv[])
{
   char *p=0;
   char *q=0;
}

static int a(char *p, char *q)
{
    p=malloc(10);
    some_method(p,q);
}

static int b(char *p, char *q)
{
   q=malloc(10);
   some_method(p,q);
}

some_method(char *p, char *q)
{
   if(p != null && q != null)
   {
     bladiebla();
   }

}
 
Old 02-08-2012, 04:00 AM   #3
Doc CPU
Senior Member
 
Registered: Jun 2011
Location: Stuttgart, Germany
Distribution: Mint, Debian, Gentoo, Win 2k/XP
Posts: 1,099

Rep: Reputation: 344Reputation: 344Reputation: 344Reputation: 344
Hi there,

Code:
static int a()
{
p = malloc(10);

someMethod(p, q);
}

static int b()
{
q = malloc(10);

someMethod(p, q);
}
Quote:
Originally Posted by akshay_satish View Post
The above snippet will work considering p & q as global pointer. Is there any way I can use p & q as local between a() & b()?
Not really, because a() and b() are totally unconnected and their own scopes don't intersect. But I gather you're trying to avoid accessing global variables out of a function, which is a good idea.

The first thing that comes to mind is changing the interface of the two functions, so that they receive the two pointers as parameters. That's tricky here, because using malloc() you change the parameters inside the function, but not outside. To circumvent this, you'd have to pass a pointer to the actual parameter to the function. Since p and q are already pointers, the formal parameter would be a pointer to a pointer:

Code:
static int a(char **u, char **v)
 { *u = malloc(10);
   someMethod(*u, *v);
 }
That looks a bit ugly, alright. But C always passes function arguments by value, there is no real "pass by reference". In C++ you could use references - it makes the code look more neat, but technically it's exactly the same. But wait, if you're looking at C++, you could do it better. Make an object (a class) that contains p and q as private members, and a() and b() as public methods. Then everything is cleanly encapsulated.

[X] Doc CPU
 
Old 02-08-2012, 04:03 AM   #4
Doc CPU
Senior Member
 
Registered: Jun 2011
Location: Stuttgart, Germany
Distribution: Mint, Debian, Gentoo, Win 2k/XP
Posts: 1,099

Rep: Reputation: 344Reputation: 344Reputation: 344Reputation: 344
Hi there,

Quote:
Originally Posted by Ramurd View Post
you can pass your pointers as arguments to your functions
what I said, only a minute later. ;-)

Code:
static int a(char *p, char *q)
{
    p=malloc(10);
    some_method(p,q);
}
But that's a catch! Inside the function, you're working with a copy of the parameter. The original values of p and q in main() remain unchanged.

[X] Doc CPU
 
Old 02-08-2012, 04:14 AM   #5
Ramurd
Member
 
Registered: Mar 2009
Location: Rotterdam, the Netherlands
Distribution: Slackwarelinux
Posts: 703

Rep: Reputation: 111Reputation: 111
Quote:
Originally Posted by Doc CPU View Post
Hi there,



what I said, only a minute later. ;-)

Code:
static int a(char *p, char *q)
{
    p=malloc(10);
    some_method(p,q);
}
But that's a catch! Inside the function, you're working with a copy of the parameter. The original values of p and q in main() remain unchanged.

[X] Doc CPU
absolutely true, should take more coffee to me before answering ;-) Listen to the doc!
 
Old 02-08-2012, 04:26 AM   #6
Nominal Animal
Senior Member
 
Registered: Dec 2010
Location: Finland
Distribution: Xubuntu, CentOS, LFS
Posts: 1,723
Blog Entries: 3

Rep: Reputation: 948Reputation: 948Reputation: 948Reputation: 948Reputation: 948Reputation: 948Reputation: 948Reputation: 948
Doc CPU, wouldn't it be better, in C, to pass a state "object" (structure) instead?
Code:
struct state {
    char *p;
    char *q;
};
#define DEFAULT_STATE {0}


static void a(struct state *const state)
{
    state->p = malloc(10);

    somefunction(state->p, state->q);
}
    

static void b(struct state *const state)
{
    state->q = malloc(10);

    somefunction(state->p, state->q);
}


int main(void)
{
    struct state somestate = DEFAULT_STATE;

    a(&somestate);

    b(&somestate);

    return 0;
}
The DEFAULT_STATE constant, {0} means the entire structure will be initialized to binary zeros. (It is standard behaviour all C compilers I know will adhere to.) On all sane architectures, that means integer and floating point zeros, NULL pointers, and empty char arrays (filled with ASCII NULs == zero bytes).

While this may be rare to see in single-threaded applications, the void * parameter at end for pthread_create(3) is very, very often used for exactly this purpose.

It is also extremely common in more complex software. You see it all the time in projects like the Linux kernel and the Apache web server, where there are multiple state objects being passed around.

I think you can see the obvious benefits from this. There are no global variables, so you can instantiate any number of states you might need. If each thread only uses their own state object, the code is automatically thread safe (except for any external libraries and perhaps side effects like I/O). If you need more state, just extend the structure. For full thread safety, you can add either state object lock, or more fine-grained locking. If you use reference counting, you can garbage-collect entire state objects relatively easily.
 
1 members found this post helpful.
Old 02-08-2012, 04:35 AM   #7
akshay_satish
Member
 
Registered: May 2011
Posts: 63

Original Poster
Rep: Reputation: Disabled
Quote:
Originally Posted by Doc CPU View Post
Hi there,

Code:
static int a()
{
p = malloc(10);

someMethod(p, q);
}

static int b()
{
q = malloc(10);

someMethod(p, q);
}

Not really, because a() and b() are totally unconnected and their own scopes don't intersect. But I gather you're trying to avoid accessing global variables out of a function, which is a good idea.

The first thing that comes to mind is changing the interface of the two functions, so that they receive the two pointers as parameters. That's tricky here, because using malloc() you change the parameters inside the function, but not outside. To circumvent this, you'd have to pass a pointer to the actual parameter to the function. Since p and q are already pointers, the formal parameter would be a pointer to a pointer:

Code:
static int a(char **u, char **v)
 { *u = malloc(10);
   someMethod(*u, *v);
 }
That looks a bit ugly, alright. But C always passes function arguments by value, there is no real "pass by reference". In C++ you could use references - it makes the code look more neat, but technically it's exactly the same. But wait, if you're looking at C++, you could do it better. Make an object (a class) that contains p and q as private members, and a() and b() as public methods. Then everything is cleanly encapsulated.

[X] Doc CPU
i am using C++
 
Old 02-08-2012, 04:40 AM   #8
akshay_satish
Member
 
Registered: May 2011
Posts: 63

Original Poster
Rep: Reputation: Disabled
I am not sure if tats a gr8 idea?

Quote:
Originally Posted by Ramurd View Post
you can pass your pointers as arguments to your functions

Code:
int main(int argc, char *argv[])
{
   char *p=0;
   char *q=0;
}

static int a(char *p, char *q)
{
    p=malloc(10);
    some_method(p,q);
}

static int b(char *p, char *q)
{
   q=malloc(10);
   some_method(p,q);
}

some_method(char *p, char *q)
{
   if(p != null && q != null)
   {
     bladiebla();
   }

}
 
Old 02-08-2012, 04:59 AM   #9
Doc CPU
Senior Member
 
Registered: Jun 2011
Location: Stuttgart, Germany
Distribution: Mint, Debian, Gentoo, Win 2k/XP
Posts: 1,099

Rep: Reputation: 344Reputation: 344Reputation: 344Reputation: 344
Hi there,

Quote:
Originally Posted by Nominal Animal View Post
Doc CPU, wouldn't it be better, in C, to pass a state "object" (structure) instead?
that's a very elegant approach, I guess.
Hadn't thought of that at first sight.

[X] Doc CPU
 
Old 02-08-2012, 05:02 AM   #10
Ramurd
Member
 
Registered: Mar 2009
Location: Rotterdam, the Netherlands
Distribution: Slackwarelinux
Posts: 703

Rep: Reputation: 111Reputation: 111
Quote:
Originally Posted by akshay_satish View Post
I am not sure if tats a gr8 idea?
and why would it be not a good idea? As you can see both Doc CPU and Nominal Animal went along this route (but by far not as crappy as I did). It's a better idea than using global variables.
 
Old 02-08-2012, 05:36 AM   #11
dwhitney67
Senior Member
 
Registered: Jun 2006
Location: Maryland
Distribution: Kubuntu, Fedora, RHEL
Posts: 1,541

Rep: Reputation: 335Reputation: 335Reputation: 335Reputation: 335
Quote:
Originally Posted by akshay_satish View Post
i am using C++
Then you shouldn't be using malloc(), but instead the new operator.

Using something similar to Nominal's example:
Code:
struct State
{
    State(char* p = 0, char* q = 0) : m_p(p), m_q(q) {}

    ~State()
    {
        delete [] m_p;
        delete [] m_q;
    }

    char* m_p;
    char* m_q;
};

class Foo
{
public:
    Foo() : m_state(new char[10], new char[10]) {}

    void a()
    {
        someMethod();
    }

    void b()
    {
        someMethod();
    }

private:
    void someMethod()
    {
        // access m_state.m_p and m_state.m_q
        ...
    }

    State m_state;
};

int main()
{
    Foo foo;
    foo.a();
    foo.b();
}

Last edited by dwhitney67; 02-08-2012 at 05:38 AM.
 
Old 02-08-2012, 10:44 AM   #12
theNbomr
LQ 5k Club
 
Registered: Aug 2005
Distribution: OpenSuse, Fedora, Redhat, Debian
Posts: 5,399
Blog Entries: 2

Rep: Reputation: 908Reputation: 908Reputation: 908Reputation: 908Reputation: 908Reputation: 908Reputation: 908Reputation: 908
It sounds like you want the two pointer variables to be visible to only the functions a() and b()
If the functions a() and b() are in their own common compilation unit (source file), then they can mutually share static variables within that source file. So, just make p & q static, and make a() and b() global.

Code:
#include <malloc.h>

void someMethod(char * p, char * q);

static char *p = 0;
static char *q = 0;

int a()
{
    p = malloc(10);

    someMethod(p, q);
}

int b()
{
    q = malloc(10);

    someMethod(p, q);
}
Now, a() and b() are callable from anywhere in your program, but the two variables are privately shared between the two fucntions.

I'm not saying this is necessarily good practice, but it does seem to answer the question.

--- rod.
 
Old 02-08-2012, 11:23 AM   #13
millgates
Member
 
Registered: Feb 2009
Location: 192.168.x.x
Distribution: Slackware
Posts: 852

Rep: Reputation: 389Reputation: 389Reputation: 389Reputation: 389
Quote:
Originally Posted by theNbomr View Post
It sounds like you want the two pointer variables to be visible to only the functions a() and b()
If the functions a() and b() are in their own common compilation unit (source file), then they can mutually share static variables within that source file. So, just make p & q static, and make a() and b() global.

Now, a() and b() are callable from anywhere in your program, but the two variables are privately shared between the two fucntions.
In C++, a similar result can be achieved using an anonymous namespace

Code:
namespace{
	char *p = 0;
       	char *q = 0;
}

int a() { p; ... }
int b() { q; ... }
or by putting the pointers into a class.

Code:
class MyClass {
    char *p;
    char *q;
public:
    int a() { p; q; ... }
    int b() { p; q; ... }
};
I suggest that you decide whether you program in C or C++ and write your code accordingly.
 
Old 02-09-2012, 01:15 AM   #14
akshay_satish
Member
 
Registered: May 2011
Posts: 63

Original Poster
Rep: Reputation: Disabled
thank you people for your valued suggestions.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
concept deepaksinghnegi Linux - Newbie 2 10-23-2009 02:56 AM
pointer to pointer segmentation fault Guilherme Programming 7 06-28-2009 09:47 AM
pass pointer,, return pointer??? blizunt7 Programming 3 07-23-2005 01:36 PM
returning data to main() via a pointer to a pointer. slzckboy Programming 3 05-30-2005 01:20 PM
hot to set value of pointer to pointer to a structure in C alix123 Programming 2 11-17-2004 06:40 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 02:06 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration