473,378 Members | 1,317 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

C passing a global pointer

Hi guys.
Let's say I've got something like this:

struct Box{
//something
};
typedef struct Box* pBox;

void fun(pBox p);

int main(){
pBox p = NULL;
fun(p);
}

void fun(pBox p){
if(p == NULL) p = (pBox)malloc(sizeof(Box));
}

function fun recieves the address(which is NULL) and then allocates the memory for the Box; Let's say I cannot return the address of new allocated p and I can't also use that pointer p(from main) without passing it into a function.

Q: How can I make it that I could operate in function "fun" as I operate on orginal pointer p(from main), right now I'm just passing the address to my function but I can't change
the 'global' pointer p ;(.

I remember in pascal it's like:
"function(var pointer:[pointer to sth])"
and all is done.

How can I do it in C?
Any ideas?
Feb 29 '12 #1

✓ answered by Banfa

Do you not get any warnings when you compile? I get the following warning compiling your code

bytes.c:15: warning: passing argument 1 of 'fun' from incompatible pointer type

You should not ignore compiler warnings, they are there to tell you when you are doing something suspect. This is one of those cases where C++ is stricter than C it would not allow that line to compile, it produces an error rather than a warning. However that is correct the compiler assumes you know what you are doing and allow the pointer conversion to go ahead.

So you pass p of type Box* to a function expecting Box**. p has the value NULL or 0 and the first thing you do is dereference it at line 8 since it is NULL the program crashes.

The warning highlights the problem, you passed type Box* to a function expecting Box**, you passed the wrong thing, you needed to dereference the pointer you were passing as the example in my first post when you want to output an int the function takes int* and you pass &a (where a is an int variable). The function is expecting pBox* so you pass &p (where p is a pBox variable).

i.e. line 15 should be fun(&p);

Don't ignore compiler warnings and if you didn't get a warning get a better compiler.

14 3600
johny10151981
1,059 1GB
Read About IPC. there is lots of way to do this.
Mar 1 '12 #2
weaknessforcats
9,208 Expert Mod 8TB
This function:

Expand|Select|Wrap|Line Numbers
  1. void fun(pBox p){
  2. etc...
makes a copy of the pointer used by the caller. What you want to do is tell the compiler to not make that copy. In C++ that is called a reference:

Expand|Select|Wrap|Line Numbers
  1. void fun(pBox& p){
  2. etc...
Now in fun, the argument p is the same pointer used by the calling function. No copy was made.
Mar 1 '12 #3
I tried "pBox& p" but it says:
'expected ';', ',', ')' before '&' token.
I'm nut sure if I can do that,
isn't it like "Box* &p"?...

Guess it's not available in C. So it's not possible to use in function 'original' pointer?(not using global pointer in functions, gotta pass them first)
Mar 1 '12 #4
weaknessforcats
9,208 Expert Mod 8TB
Did you change both the function and the prototype?

Here is your code with the change and it compiles OK:
Expand|Select|Wrap|Line Numbers
  1. struct Box{
  2.  //something
  3.  };
  4.  typedef struct Box* pBox;
  5.  
  6. void fun(pBox& p);
  7.  
  8. int main(){
  9.  pBox p = NULL;
  10.  fun(p);
  11.  }
  12.  
  13. void fun(pBox& p){
  14.  if(p == NULL) p = (pBox)malloc(sizeof(Box));
  15.  }
Mar 1 '12 #5
Banfa
9,065 Expert Mod 8TB
Expand|Select|Wrap|Line Numbers
  1. void fun(pBox& p)
This doesn't work because it is a reference which is only supported by C++, a solution in C is required. And that is simple, just use a pointer to a pointer.

Whenever you want to output some type but not use the return value you need a pointer to that type in your function prototype, for int

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.   int a;
  4.  
  5.   getValue(&a);
  6.  
  7.   printf("The value is: %d\n", a);
  8.  
  9.   return 0;
  10. }
  11.  
  12. void getValue(int* pValue)
  13. {
  14.   *pValue = 10;
  15. }
  16.  
This is true for any type and can generalised for any type A as


Expand|Select|Wrap|Line Numbers
  1. void getValue(A* pValue)
  2. {
  3.   *pValue = <ValidValueForTypeA>;
  4. }
  5.  
In your case you want to pass out a variable of type pBox so in the code above A = pBox and you need this prototype void fun(pBox* p).

In full your function becomes

Expand|Select|Wrap|Line Numbers
  1. void fun(pBox* p)
  2. {
  3.   if(*p == NULL)
  4.   {
  5.     *p = malloc(sizeof(Box));
  6.   }
  7. }
  8.  
Note the is no need and indeed it can cause subtle errors if you cast the return value of malloc in C.
Mar 2 '12 #6
weaknessforcats
9,208 Expert Mod 8TB
Expand|Select|Wrap|Line Numbers
  1. fun(pBox* p)
  2.  2. {
  3.  3.   if(*p == NULL)
  4.  4.   {
  5.  5.     *p = malloc(sizeof(Box));
  6.  6.   }
  7.  7. }
  8.  
This won't work because p is a Box* so *p s a Box.

I believe you want:
Expand|Select|Wrap|Line Numbers
  1. fun(pBox** p)
  2.   {
  3.    if(*p == NULL)
  4.     {
  5.       *p = malloc(sizeof(Box));
  6.    }
  7.   }
  8.  
Now p is a pointer to a Box* so *p is now a Box*.
Mar 2 '12 #7
Banfa
9,065 Expert Mod 8TB
This won't work because p is a Box* so *p s a Box.
No p is pBox* and pBox is typedef'd to Box*, making p a Box**, just what is wanted. If you use pBox** p then p would be Box*** which would be indirection gone mad :D
Mar 5 '12 #8
why does it give me runtime error when I try go with '*p == NULL'?
Mar 5 '12 #9
Banfa
9,065 Expert Mod 8TB
You probably call the function with the wrong variable type, you are trying to write a variable of type pBox so you need to declare a pBox in main.
Mar 5 '12 #10
okay, what I do wrong?:

Expand|Select|Wrap|Line Numbers
  1. typedef struct {
  2.  int n;
  3. }Box;
  4. typedef struct Box* pBox;
  5.  
  6. void fun(pBox* p)
  7. {
  8.   if(*p == NULL)
  9.   {
  10.     *p = malloc(sizeof(Box));
  11.   }
  12. }
  13.  int main(){
  14.     pBox p = NULL;
  15.     fun(p);
  16. }
still got that error in '*p == NULL', can someone compile this and check, it kills me...
Mar 7 '12 #11
weaknessforcats
9,208 Expert Mod 8TB
You need to #include <stdio.h> in order to get NULL declared.

You may have other warnings which indicate a weakness in the code. Ideally, you should have no errors and no warnings.
Mar 7 '12 #12
yes, I included libs but the problem comes when I run the program.
It appears runtime error and points the line with NULL. But I guess it's sth wrong with the *p == null because when I change it to 'p' it works.
Mar 7 '12 #13
Banfa
9,065 Expert Mod 8TB
Do you not get any warnings when you compile? I get the following warning compiling your code

bytes.c:15: warning: passing argument 1 of 'fun' from incompatible pointer type

You should not ignore compiler warnings, they are there to tell you when you are doing something suspect. This is one of those cases where C++ is stricter than C it would not allow that line to compile, it produces an error rather than a warning. However that is correct the compiler assumes you know what you are doing and allow the pointer conversion to go ahead.

So you pass p of type Box* to a function expecting Box**. p has the value NULL or 0 and the first thing you do is dereference it at line 8 since it is NULL the program crashes.

The warning highlights the problem, you passed type Box* to a function expecting Box**, you passed the wrong thing, you needed to dereference the pointer you were passing as the example in my first post when you want to output an int the function takes int* and you pass &a (where a is an int variable). The function is expecting pBox* so you pass &p (where p is a pBox variable).

i.e. line 15 should be fun(&p);

Don't ignore compiler warnings and if you didn't get a warning get a better compiler.
Mar 7 '12 #14
Oh, now I see... should have read your previous reply better. And thanks for advice with the warnings, I simply didn't care what they said thinking it's not the case of my problem.
Thanks for help. ;D
Mar 7 '12 #15

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Newsgroup - Ann | last post by:
Gurus, I have the following implementation of a member function: class A { // ... virtual double func(double v); void caller(int i, int j, double (* callee)(double)); void foo() {caller(1,...
31
by: Andrej Prsa | last post by:
Hi! What happens to a globally defined pointer, e.g. void *value; that points to a particular type in a function: int dummy_func (int a) {
17
by: Charles Sullivan | last post by:
The library function 'qsort' is declared thus: void qsort(void *base, size_t nmemb, size_t size, int(*compar)(const void *, const void *)); If in my code I write: int cmp_fcn(...); int...
2
by: Lupina | last post by:
How to do global pointer , which indicates on the second form ? If I want e.g. invoke another form I do it like this : private: System::Void menuItemDlg_Click(System::Object * sender,...
4
by: entitledX | last post by:
Hi, I'm trying to use the HDF library to read a few HDF files that I need to process. The data in each file varies in rows, but the columns remain constant. Because of that, I had dynamically...
2
by: mark.e.nelson | last post by:
Hi, I am trying to pass a pointer to a struct to a function that uses the data in the struct, and also happens to use ncurses. I always get a segmentation violation when the program exits. I...
3
by: dice | last post by:
Hi, In order to use an external api call that requires a function pointer I am currently creating static wrappers to call my objects functions. I want to re-jig this so I only need 1 static...
5
by: mshaaban | last post by:
Hello, In my code I have a large static 2D arrays defined as: code: #define LONMAX 1440 #define LATMAX60 480 void main (int argc, char *argv)
6
by: iamstein | last post by:
Hi, I would like to declare a global pointer. I have started with this very simple code, which does not work. I am using Xcode on a Mac running Tiger (10.4) double *F; int main () { double...
5
by: miner | last post by:
Hi all I'm doing my first steps in C and I need some help plz. I have 2 structs, a node* and a stack*. I want to write a push() function that accepts to arguments, the node to insert and the...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.