473,671 Members | 2,588 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Pointer to pointer with lots of examples

Can anyone help me in getting to understand pointer to pointer with
examples?

Appritiate in advance.

Sagar

Jul 30 '06 #1
14 1887
sheroork said:
Can anyone help me in getting to understand pointer to pointer with
examples?
Phone up the Directory Enquiries service (192 if you're in the UK). Tell
them the name of the person you're looking for, and they'll tell you the
relevant phone number. You can then use that phone number to contact the
person you really want to talk to.

Translation: a pointer tells you where something is. But it, itself, has an
address, which you might need to find out before you can use it. So a
pointer to pointer simply tells you where a particular pointer is. A
pointer is like a phone number. Dereferencing the pointer is like making
the call. When the guy on the other end gives you another phone number,
you've just used a pointer (*his* number) to a pointer (the number he gives
you), and presumably you'll use that new pointer to find the information
(make the call) you really wanted to find (make).

Examples are tricky, in that any realistic working example is likely to be
way too big and complicated to make it a useful example. If you're not
afraid of big examples, though, let me know and I'll see what I can dig up
from my code base.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jul 30 '06 #2
sheroork wrote:
Can anyone help me in getting to understand pointer to pointer with
examples?
int **p;

p
+---+
| ? |
+---+

p = malloc(sizeof *p);

p *p
+---+ +---+
| ----->| ? |
+---+ +---+

*p = malloc(sizeof **p);

p *p **p
+---+ +---+ +---+
| ----->| ----->| ? |
+---+ +---+ +---+

**p = 7;

p *p **p
+---+ +---+ +---+
| ----->| ----->| 7 |
+---+ +---+ +---+
August
Jul 30 '06 #3
Richard Heathfield <in*****@invali d.invalidwrites :
sheroork said:
>Can anyone help me in getting to understand pointer to pointer with
examples?

Examples are tricky, in that any realistic working example is likely to be
way too big and complicated to make it a useful example. If you're not
afraid of big examples, though, let me know and I'll see what I can dig up
from my code base.
Using a pointer to pointer to return a pointer value from a
function may be a simple way to come up with a short example.
--
int main(void){char p[]="ABCDEFGHIJKLM NOPQRSTUVWXYZab cdefghijklmnopq rstuvwxyz.\
\n",*q="kl BIcNBFr.NKEzjwC IxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+= strchr(p,*q++)-p;if(i>=(int)si zeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Jul 30 '06 #4
Ben Pfaff said:
Richard Heathfield <in*****@invali d.invalidwrites :
>sheroork said:
>>Can anyone help me in getting to understand pointer to pointer with
examples?

Examples are tricky, in that any realistic working example is likely to
be way too big and complicated to make it a useful example. If you're not
afraid of big examples, though, let me know and I'll see what I can dig
up from my code base.

Using a pointer to pointer to return a pointer value from a
function may be a simple way to come up with a short example.
Be my guest. :-)

The problem with such examples, however, is that they tend to leave the
reader scratching his head and thinking "okay, I'm seeing some syntax, and
I think I understand that - but why would anyone do it like /that/ when
they could just, say, return the pointer value using 'return p;'?" You know
and I know that such code as foo(&ptr) is actually quite common, and for
good reason - but it's one thing to know and another to explain.

Maybe August had the right idea - a dynamic array of dynamic arrays.

T **p = malloc(rows * sizeof *p);
if(p != NULL)
{
size_t r = 0;
for(r = 0; r < rows; r++)
{
p[r] = malloc(cols * sizeof *p[r]);
if(p[r] == NULL) { handle_the_erro r(); }
}

Assuming all that worked okay, you now have a dynamically sized array, rows
* cols elements in size. Whilst there are other ways to achieve this, I
think pointer to pointer is actually the simplest solution for this
problem, so it makes a good example. Nice one, August.
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jul 30 '06 #5
Richard Heathfield <in*****@invali d.invalidwrites :
Maybe August had the right idea - a dynamic array of dynamic arrays.
There is in an example of a multidimensiona l array using a
pointer-to-pointer in the FAQ. I thought about posting it
earlier but wasn't sure that it was simple enough.

6.16: How can I dynamically allocate a multidimensiona l array?

A: The traditional solution is to allocate an array of pointers,
and then initialize each pointer to a dynamically-allocated
"row." Here is a two-dimensional example:

#include <stdlib.h>

int **array1 = malloc(nrows * sizeof(int *));
for(i = 0; i < nrows; i++)
array1[i] = malloc(ncolumns * sizeof(int));

(In real code, of course, all of malloc's return values would
be checked.)

You can keep the array's contents contiguous, at the cost of
making later reallocation of individual rows more difficult,
with a bit of explicit pointer arithmetic:

int **array2 = malloc(nrows * sizeof(int *));
array2[0] = malloc(nrows * ncolumns * sizeof(int));
for(i = 1; i < nrows; i++)
array2[i] = array2[0] + i * ncolumns;

In either case, the elements of the dynamic array can be
accessed with normal-looking array subscripts: arrayx[i][j]
(for 0 <= i < nrows and 0 <= j < ncolumns).

If the double indirection implied by the above schemes is for
some reason unacceptable, you can simulate a two-dimensional
array with a single, dynamically-allocated one-dimensional
array:

int *array3 = malloc(nrows * ncolumns * sizeof(int));

However, you must now perform subscript calculations manually,
accessing the i,jth element with array3[i * ncolumns + j]. (A
macro could hide the explicit calculation, but invoking it would
require parentheses and commas which wouldn't look exactly like
multidimensiona l array syntax, and the macro would need access
to at least one of the dimensions, as well. See also question
6.19.)

Yet another option is to use pointers to arrays:

int (*array4)[NCOLUMNS] = malloc(nrows * sizeof(*array4) );

but the syntax starts getting horrific and at most one dimension
may be specified at run time.

With all of these techniques, you may of course need to remember
to free the arrays (which may take several steps; see question
7.23) when they are no longer needed, and you cannot necessarily
intermix dynamically-allocated arrays with conventional,
statically-allocated ones (see question 6.20, and also question
6.18).

Finally, in C9X you can use a variable-length array.

All of these techniques can also be extended to three or more
dimensions.

References: C9X Sec. 6.5.5.2.

--
"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Jul 30 '06 #6

August Karlstrom wrote:
sheroork wrote:
Can anyone help me in getting to understand pointer to pointer with
examples?

int **p;

p
+---+
| ? |
+---+

p = malloc(sizeof *p);

p *p
+---+ +---+
| ----->| ? |
+---+ +---+

*p = malloc(sizeof **p);
ITYM: *p=malloc(sizeo f int);

p *p **p
+---+ +---+ +---+
| ----->| ----->| ? |
+---+ +---+ +---+

**p = 7;

p *p **p
+---+ +---+ +---+
| ----->| ----->| 7 |
+---+ +---+ +---+
August
Sharath A.V

-In the journey of life, failure is a lesson and success is an illusion.

Jul 31 '06 #7
Scorpio said:
August Karlstrom wrote:
<snip>
>>
*p = malloc(sizeof **p);

ITYM: *p=malloc(sizeo f int);
No, HDNMT. For one thing, August's code is conceptually correct no matter
what the object type to which p points. And secondly, his code - unlike
yours - will actually compile.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jul 31 '06 #8
Richard Heathfield wrote:
Scorpio said:
August Karlstrom wrote:
<snip>
>
*p = malloc(sizeof **p);
ITYM: *p=malloc(sizeo f int);

No, HDNMT. For one thing, August's code is conceptually correct no matter
what the object type to which p points. And secondly, his code - unlike
yours - will actually compile.
Sorry, I was mistaken and yes, August's code is correct.
But I actually meant: *p=malloc(sizeo f(int));
Is something wrong with this?

Even the code quoted by Ben from the FAQ is as follows:
int **array1 = malloc(nrows * sizeof(int *));
for(i = 0; i < nrows; i++)
array1[i] = malloc(ncolumns * sizeof(int));

BTW, what does HDNMT mean? I did try to find out, but found no results.

Sharath A.V

Jul 31 '06 #9
Scorpio said:
Richard Heathfield wrote:
>Scorpio said:
August Karlstrom wrote:
<snip>
>>
*p = malloc(sizeof **p);

ITYM: *p=malloc(sizeo f int);

No, HDNMT. For one thing, August's code is conceptually correct no matter
what the object type to which p points. And secondly, his code - unlike
yours - will actually compile.

Sorry, I was mistaken and yes, August's code is correct.
But I actually meant: *p=malloc(sizeo f(int));
Is something wrong with this?
It will at least compile, but it's inferior to August's version, because
you're nailing the type to the call, possibly causing a maintenance
headache further down the line.
Even the code quoted by Ben from the FAQ is as follows:
int **array1 = malloc(nrows * sizeof(int *));
for(i = 0; i < nrows; i++)
array1[i] = malloc(ncolumns * sizeof(int));
Yeah, the FAQ is good but nobody ever claimed it was perfect.
BTW, what does HDNMT mean? I did try to find out, but found no results.
He Did Not Mean That. (i.e. he did not mean what you thought he meant.)

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jul 31 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
7307
by: Hilary Zhang | last post by:
Hi, I have a headache with my program, which is a real-time graphic program written in VC++ 6.0. I often get an error of "access violation" when run in release mode. But if I use debug mode, it seldom happens since the debug mode is much slower than the release mode and the possible bug won't show up. I think it may be problem with my usage of pointers. I just wonder is there a way to validate a pointer, when it is 0xcdcdcd or 0xffffffff...
20
4364
by: m sergei | last post by:
Question is about the difference between these two reference to an object versus pointer to an object What are advantages in either one and when would one use them. I see lots of examples when an object is passed as a parameter to a function it is passed as a reference. Though it would have been fine to pass it as a pointer as well ? is that right ? I had posted a similar question in the C lang newsgroup but did not get much help as C...
33
17526
by: siliconwafer | last post by:
What is size of pointer in C on DOS? is it sizeof(int ) or size of (long int)? If this ans is present in FAQ pls direct me to tht ouestion
30
1863
by: Joe Smith | last post by:
A recent post of mine showed a sufficiently large gaffe on pointers as to need to return to K&R 5.1-6 appendix A8.6.1 . So we have type specifiers: int long .. One dreams himself variable names: qwe, qwr, writes int qwe; long qwr; and thinks he knows what types he's declared. Had you asked me about:
5
1306
by: Gonçalo Rodrigues | last post by:
Hi all, Is it true that all pointer types that can be cast into void* (that is, all pointer types with the exception of pointers to functions and pointers to members) have the same size? And if not, do you know of any examples of platform (OS + compiler) where such happens? And does standard C++ guarantee the existence of a primitive (signed) integer type T such that
42
5317
by: xdevel | last post by:
Hi, if I have: int a=100, b = 200, c = 300; int *a = {&a, &b, &c}; than say that: int **b is equal to int *a is correct????
9
3013
by: junky_fellow | last post by:
Hi, To print the pointer using printf(), we convert it to (void *) . printf("%p",(void *)ptr); My question is how printf() determine which type of pointer is passed to it and prints its value accordingly ? I have this doubt as different pointers may have different representation and different size. So, how does printf determine
30
3589
by: ggnguser | last post by:
It's part of a test and I'm stumped. There is a function void foo(char **x) The function signature is given and cannot be changed, so no passing of other values. The test case involves defining this variable: char *y = { /* bunch of stuff */ } and calling
6
8539
by: sasha | last post by:
I have a c++ code that callls csharp. Now I want to be able to pass a function pointer from C++ to Csharp code and have c# callback to it. Is it possible and how? Here is what I have so far : #include "windows.h" #include <stdio.h> #import "CSDll.tlb" named_guids int main(int argc, char* argv)
0
8930
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8828
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8677
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7446
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6238
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5704
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4227
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2819
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1816
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.