What does this symbol ** mean in the C language - c

Hi I'm new to the C language, can someone explains what ** symbol mean.
typedef struct _TREENODE {
struct _TREENODE *Left, *Right;
TCHAR key[KEY_SIZE];
LPTSTR pData;
} TREENODE, *LPTNODE, **LPPTNODE;

If x is a pointer, *x dereferences it. **x is the same as *(*x), so **x dereferences a pointer to a pointer. (eg, it is the thing that is pointed to by the thing that x opints to).

** is a pointer to pointer, it is also used for dereferencing a pointer variable.
eg: int a=10,*b,**c;
b=&a;
c=&b;
printf("the a value is:%d\n",a);
printf("the b value is:%d\n",*b);
printf("the c value is:%d\n",**c);
just execute this code you will get the idea about pointer to pointer.

In you want to change a variable, you pass it by pointer (to the variable).
And if you want to change a pointer, you also pass it by pointer (to the pointer) which is a double pointer.

There are two things to know about * in C:
It's an operation. Doing *x on a pointer dereferences that pointer. Doing **x on a pointer can dereference a pointer to a pointer, and so on.
It's a type. Declaring a type of int *x means that it's a pointer to an int type. Declaring int **x means that it's a pointer to a pointer to an int type.
Example:
int main() {
int foo = 4;
int *bar = &foo; // declaring a pointer to int type *bar
int **baz = &bar; // declaring a pointer to a pointer to int type **baz
printf("foo: %d, *bar: %d, **baz: %d\n", foo, *bar, **baz); // derefencing the pointer *bar and **baz
return 0;
}

In a declaration, ** means pointer to a pointer. When evaluating an expression, ** dereferences a pointer to a pointer.
int** p; // Declares p to be a pointer to a pointer.
And...
**p = 10; // Dereferences p and assigns 10 to a memory location.
One common use of pointers to pointers is to represent dynamic 2D arrays. For example, if you want to create a matrix of M rows and N columns, you could do:
int** matrix = malloc(M*sizeof(*matrix));
int i = 0, j = 0;
for ( i = 0; i < M; ++i )
matrix[i] = malloc(N*sizeof(*matrix[0]));
Usage of the double pointer:
for ( i = 0; i < M; ++i )
for ( j = 0; j < N; ++j )
matrix[i][j] = 0; // Assigns a value to the element
// at the i-th row and j-th column.
If you want to use string pointer dereferencing, you would use:
for ( i = 0; i < M; ++i )
for ( j = 0; j < N; ++j )
*(*(matrix+i)+j) = 0;
Memory allocated for the matrix has to be freed in two passes also.
for ( i = 0; i < M; ++i )
free(matrix[i]);
free(matrix);

** means a pointer to a pointer.
Most of the time I like to think of it as "pointer(s)" to "a memory area". Which in fact may be a little redundant.
For example, suppose you have to dynamically store several words on memory, how would you do that? There are several ways to do this, but I'll provide an example that illustrate the use of **.
Now, suppose you want to store three words: hi, hello and goodbye
hi, hello and goodbye are strings, they consume, 2, 5 and 7 bytes on memory respectively. Well, in fact it's 3, 6 and 8 bytes because of the \0, but lets not get into many details.
But one thing is clear, we need three memory areas to hold these strings and also three pointers to reference these memory areas later.
Note that one can just declare three pointers that points to these memory areas, but, would you be willing to declare one thousand pointers to hold one thousand words? This is where ** kicks in.
Example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUMBER_OF_WORDS 3
int
main(int argc, char **argv)
{
int i;
char **words;
/* pointers */
words = malloc(sizeof(char*)*NUMBER_OF_WORDS);
/* memory areas*/
words[0] = strdup("Hi");
words[1] = strdup("Hello");
words[2] = strdup("Goodbye");
for(i=0; i < NUMBER_OF_WORDS; i++)
printf("%d) %s\n", i, words[i]);
for(i=0; i < NUMBER_OF_WORDS; i++)
free(words[i]); /* memory area */
free(words); /* pointers */
return 0;
}

Related

dereference a pointer to a pointer casted from array pointer

Learning C and this confusing me:
#include <stdio.h>
int main(){
int m[5][5];
int count = 0;
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
m[i][j] = count++;
}
}
int **p = m;
int (*k)[5] = m;
printf("%p\t%p\t%p", *p, *k, *m);
return 0;
}
that's what has been printed:
0x100000000 0x7ffff1fc9d70 0x7ffff1fc9d70
I'm really confused why dereference *p is 0x100000000, shouldn't it be 0x7ffff1fc9d70?
You’re thinking that m is of type int **, right?
It’s not. If you had done this, it would be:
int *m[5];
That make an array of five pointers to int, so m would be pointer to pointer to int.
However, if you do this:
int m[5][5];
You get enough space for 25 ints, which the compiler will access as a 5x5 two-dimensional array. p points to the beginning of that array. Dereference it, and the compiler reads the beginning of that array and interprets it as a pointer to int. Change the numbers you’re filling it with, and you’ll get different pseudo-pointers.

what's *p when p is declared as int (*)[size] and assigned to an array

code:
int arr[5] = {1,2,3,4,5};
int (*p)[5] = &arr;
printf("p:%p\n",p);
printf("*p:%p\n",*p);
result: p = *p = arr = 0x7ffee517c830 they are all the address of the array
The right way to use p to visit arr[i] is *(*p+i)
The type of pointer p is int(*)[5], so p point to an array which type is int [5]. But we can't say that p point to an invisible shell of arr, p is a variable after all. It stores the address of arr, which is also the address of arr[0], the first element of arr.
I thought *p will get me 1, which is the first element of arr.
The dereference operation means take the value in p as address and get the value from this address. Right?
So p stores the address of arr,which is 0x7ffee517c830 here, and 1 is stored in this address. Isn't **p illegal? The first dereference give us 1, and second dereference will use 1 as address which is illegal.
What I am missing?
The result of *p is an lvalue expression of array type. Using (*p) is exactly the same as using arr in any expression you could now think of.
For example:
&*p means &arr
**p means *arr (which is legal).
(*p)[i] means arr[i].
sizeof *p means sizeof arr.
Arrays are not special in this regard. You can see the same phenomenon with int x; int *q = &x;. Now *q and x have exactly the same meaning.
Regarding your last paragraph, I think you are confusing yourself by imagining pointers as glorified integers. Some people teach pointers this way but IMO it is not a good teaching technique because it causes the exact confusing you are now having.
If you dereference an int(*)[5] you get an int[5] and that's all there is to it. The data type matters in dereferencing. It does not make sense to talk about "dereferencing 0x7ffee517c830". Again this is not peculiar to arrays; if you dereference a char ***, you get a char ** etc.
The only way in which arrays are "different" in this discussion is what happens if you try to do arithmetic on them, or output them, etc. If you supply an int[5] as a printf argument for example, there is implicit conversion to int * pointing at the first of those 5 ints. This conversion also happens when applying the * operator to an int[5], which is why you get an int out of that.
p is declared as a 'pointer to int[5]'.
arr is declared as an 'int[5]`
so the initializer p = &arr; is not really that strange. If you substituted any primitive type for int[5] you wouldn't bat an eye.
*p is another handle on arr. so (*p)[0] = 1.
This really only comes up in wierd cases. It's most natural where you dereference the pointer-to-array using the subscript operator. Here's a contrived example where I want to pass a table as argument.
#include <stdio.h>
int print_row_range(int (*tab) [2], int first, int last)
{
int i;
for(i=first; i<= last; i++)
{
printf("{%d, %d}\n", tab[i][0], tab[i][1]);
}
}
int main(int argc, char *argv[])
{
int arr[3][2] = {{1,2},{3,4},{5,6}};
print_row_range(arr,1,2);
}
This example treats the table as an array of rows.
Dereferencing doesn't give you a value. It gives you an object, which can be used as a value of its type if it can be converted to.
*p, being identical to arr, is an object of an array of 5 ints, so if you want to get an integer from the array, you must dereference it again like (*p)[3].
Consider a bigger example:
int arr[5][5];
int (*p)[5] = arr;
Now you get arr[0] with *p, which itself is an array of 5. Here comes the difference:
*( p+1) == arr[1];
*(*p+1) == arr[0][1];
^ ^^^
Got the point?
One use case is to be able to allocate with malloc an 2D (or more) pointer of arrays with only one malloc:
#include <stdio.h>
#include <stdlib.h>
static int (*foo(size_t n))[42] {
return malloc(sizeof *foo(0) * n);
// return malloc(sizeof(int [n][42]); works too
}
int main(void) {
size_t n = 42;
int (*p)[42] = foo(n);
if (!p) {
return 1;
}
printf("p:");
int accu = 0;
for (size_t i = 0; i < n; i++) {
for (size_t j = 0; j < sizeof *p / sizeof **p; j++) {
p[i][j] = accu++;
printf(" %d", p[i][j]);
}
}
printf("\n");
free(p);
}
I think this very funny.
One more with VLA:
#include <stdio.h>
#include <stdlib.h>
static void *foo(size_t elem, size_t n, size_t m) {
return malloc(elem * n * m);
}
int main(void) {
size_t n = 42;
int (*p)[n] = foo(sizeof **p, n, n);
if (!p) {
return 1;
}
printf("p:");
int accu = 0;
for (size_t i = 0; i < n; i++) {
for (size_t j = 0; j < sizeof *p / sizeof **p; j++) {
p[i][j] = accu++;
printf(" %d", p[i][j]);
}
}
printf("\n");
free(p);
}

how to increment an array in c

I am trying to increment an int array using a variable as the increment but it throws an error.
int array[MAXSIZE];
int n;
//fill the array with some numbers
//some other code
The situation here is that once I analyze the first "n" numbers i will not need them again and it will be a waste of cycles to iterate the array from the starting so i want to increment the array by "n".
NOTE: because of the type of the problem that I'm working on I cannot just
save the position in a variable and start from that position later using array[position]; I have to increment the pointer permanently.
array += n;
and Throws this error: incompatible type in assignment.
I don't know in advance what "n" is going to be. I tried to use
array += sizeof(int)*n; but it fails as well.
int array[MAXSIZE];
array is an array and not a pointer. You can not increment an array variable.
You can do something like:
int *p = array;
p += whatever;
just make sure that you don't deference p when it is pointing to any element beyond the last element of the array.
The fact that printing out array and p will give you the same output (address) does not make them the same things.
According to the C Standard (6.3.2.1 Lvalues, arrays, and function designators)
3 Except when it is the operand of the sizeof operator or the unary &
operator, or is a string literal used to initialize an array, an
expression that has type ‘‘array of type’’ is converted to an
expression with type ‘‘pointer to type’’ that points to the initial
element of the array object and is not an lvalue. If the array
object has register storage class, the behavior is undefined.
So you may not change an array such a way as
array += n;
So just use one more variable of the type int *. For example
int array[MAXSIZE];
int n;
//...
int *p = array;
p += n;
an array name is a type * const array_name so you can't move it.(pay attention it is a const pointer)
you can define a pointer yourself and then move it. for example:
int *arr = new int[siz];
or in c:
int *arr = (int *)malloc(n * sizeof(int));
if your source code is in a .c file, you do not need to do casting.
If you are trying to fill the array with data, then you will need to index into the array.
int array[MAXSIZE];
int i;
for (i = 0; i < MAXSIZE; i++) {
array[i] = rand();
}
If you genuinely want to make use of a pointer, and do 'pointer arithmetic' then you must be careful.
int array[MAXSIZE];
int *p;
int i;
p = &(array[0]);
for (i = 0; i < MAXSIZE; i++) {
*p = rand();
p += 1;
}
Pointer arithmetic may not work as you expect... Doing p += 1 does not move the pointer along one byte, or even one int, but it will move the address along the size of the variable's de-referenced type.
Do an experiment:
#include <stdio.h>
void main(void) {
struct info {
int a;
int b;
};
struct info array[10];
struct info *p;
int n;
p = &(array[0]);
printf("sizeof(*p): %zu\n", sizeof(*p));
for (n = 0; n < 10; n++) {
printf("address: %p\n", p);
p += 1;
}
}
This will advance p's value by sizeof(*p) each time around the loop.
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
int main()
{
int array*,i,n;
printf("Enter size of array:\n");
scanf("%d",&n);
array = malloc(n*sizeof(int));
/* code to enter numbers in array */
array += n;
//remember to free pointers after you are done with them
free(array);
return 0;
}
This should do it.

Generic bidimensional array

I want to create a bidimensional array like so:
void **mdeclaraMatrice(int nrLini,int nrColoane, int sizeOfElement)
{
int i;
void **m = malloc(nrLini * 4);
if(m==NULL)
return NULL;
for(i=0; i<nrLini; i++)
{
*(m + (i*4)) = malloc(nrColoane * sizeOfElement);
if(*(m + (i*4)) == NULL)
return NULL;
}
return m;
}
I whant to use it like this:
int **m = (int **)mdeclaraMatrice(n,m,sizeof(int));
but it doesn't work. What do I do wrong?
You should use m[i] instead of *(m+i*4) and let the compiler do the arithmetic.
In addition, you should deallocate the already-allocated memory in case of a failure.
Try this instead:
void **mdeclaraMatrice(int nrLini, int nrColoane, int sizeOfElement)
{
int i;
void **m = malloc(nrLini * sizeof(void*));
if (m == NULL)
return NULL;
for (i=0; i<nrLini; i++)
{
m[i] = malloc(nrColoane * sizeOfElement);
if (m[i] == NULL)
{
while (i-- > 0)
free(m[i]);
free(m);
return NULL;
}
}
return m;
}
[not an answer to the question, but to the indented usage of the proper answer as given by others]
To access the void pointer array as an array of int, doing this
int **m = (int **)mdeclaraMatrice(n,m,sizeof(int));
is not correct, as per the C-Standard only void* converts to any other pointer properly, void** doesn't necessarily. So it shall correctly be
void ** ppv = mdeclaraMatrice(n,m,sizeof(int));
int * pi = *ppv; /* Please note, there is NO casting necessary here! */
Then access the members like so:
pi[0] = 42
pi[1] = 43;
...
Which essently is the same as doing
*((int *) (pi + 0)) = 42;
*((int *) (pi + 1)) = 43;
which indeed does not make sense really as pi already is int*, so the fully correct approach (also taking into account the 2nd dimension) would be:
((int *)(ppv[0]))[0] = 42;
((int *)(ppv[0]))[1] = 43;
Which could be made usable by definging a macro:
#define GENERIC_ARRAY_ELEMENT(type, address, r, c) \
((type *)(address[r]))[c]
GENERIC_ARRAY_ELEMENT(int, ppv, 0, 0) = 42;
GENERIC_ARRAY_ELEMENT(int, ppv, 0, 1) = 43;
I will address the problem of allocation an array of void pointers and then interpreting them as an array of int pointers.
int **nope = (int **)mdeclaraMatrice(n,m,sizeof(int));
Even assuming the allocation was completely correct the assignment and later usage of nope is undefined behavior. void** and int** have incompatible types.
What you can do is the following. Assign the void pointers one by one to an array of int pointers.
void** arrp = mdeclaraMatrice(n,m,sizeof(int));
int* arr[n] ;
for( size_t i = 0 , i < n ; i++ )
arr[i] = arrp[i] ;
And then use the arr array, When you want to free the memory you free the original pointer:
free( arrp ) ;
The problem occurs in this line:
*(m + (i*4)) = malloc(nrColoane * sizeOfElement);
You have to know that when adding a number to an address, the address will be incremented by the number times the size of the object the address points to. So if your pointer points to an object that is of size 4 bytes, and you add 1 to it, then the address will automatically be incremented by 4, not by 1. So you should abandon *4.
Also, use the sizeof operator when allocating space, because addresses (and thus pointers) can have different sizes on different processor architectures.
Actually, you don't even need your generic 2D array function if you know the powerfull VLA features of C99. To allocate a true 2D array (no index array required), you just do this:
int (*twoDIntArray)[width] = malloc(height*sizeof(*twoDIntArray));
That's it. Accesses are just as simple:
twoDIntArray[line][column] = 42;
In this code, twoDIntArray is a pointer to an array of width integers. The malloc() call simply allocates enough space for height such line arrays. When you do the pointer arithmetic twoDIntArray[line], you add the size of line line arrays to the pointer, which produces the address of the corresponding line array. This line array is then indexed by the second array subscript [column].
Needless to say that freeing such an array is just as trivial:
free(twoDIntArray);

Why am I getting segmentation fault for malloc() while using pointer to pointer?

I don't understand why this works:
void main() {
int * b;
b = (int *)malloc(sizeof(int));
*b = 1;
printf("*b = %d\n", *b);
}
while this does not (gets segmentation fault for the malloc()):
void main() {
int ** a;
int i;
for (i = 0; i<= 3; i++) {
a[i] = (int*)malloc(sizeof(int));
*(a[i]) = i;
printf("*a[%d] = %d\n", i, *(a[i]));
}
}
since I find a[i] is just like b in the first example.
BTW, a[i] is equal to *(a+i), right?
You need to allocate memory for a first, so that you can access its members as a[i].
So if you want to allocate for 4 int * do
a = malloc(sizeof(int *) * 4);
for (i = 0; i<= 3; i++) {
...
}
or define it as array of integer pointers as
int *a[4];
a is a 2 dimensional pointer, you have to allocate both dimension.
b is a 1 dimensional pointer, you have to allocate only one dimension and that's what you're doing with
b = (int *)malloc(sizeof(int));
So in order the second example to work you have to allocate the space for the pointer of pointer
void main() {
int ** a;
int i;
a = (int**)malloc(4*sizeof(int*));
for (i = 0; i<= 3; i++) {
a[i] = (int*)malloc(sizeof(int));
*(a[i]) = i;
printf("*a[%d] = %d\n", i, *(a[i]));
}
The allocated pointer is written to uninitialized memory (you never set a to anything), causing undefined behavior.
So no, it's not at all equivalent to the code in the first example.
You would need something like:
int **a;
a = malloc(3 * sizeof *a);
first, to make sure a holds something valid, then you can use indexing and assign to a[0].
Further, this:
a[i] = (int*)malloc(sizeof(int));
doesn't make any sense. It's assigning to a[i], an object of type int *, but allocating space for sizeof (int).
Finally, don't cast the return value of malloc() in C.
actually malloc it's not that trivial if you really want safe and portable, on linux for example malloc could return a positive response for a given request even if the actual memory it's not even really reserved for your program or the memory it's not writable.
For what I know both of your examples can potentially return a seg-fault or simply crash.
#ruppells-vulture I would argue that malloc is really portable and "safe" for this reasons.

Resources