I'm trying to better understand memcpy. Here's an example I was experimenting with:
int arr[] = {10, 20, 30, 40};
int dest[] = {1, 2, 3, 4};
void *ptr = &dest;
printf("Before copy: %d, %d, %d, %d\n", *(int*)ptr, *(int*)ptr + 1, *(int*)ptr + 2, *(int*)ptr + 3);
memcpy(dest, arr, 3*sizeof(int));
printf("After copy: %d, %d, %d, %d\n", dest[0], dest[1], dest[2], dest[3]);
printf("After copy: %d, %d, %d, %d\n", *(int*)ptr, *(int*)ptr + 1, *(int*)ptr + 2, *(int*)ptr + 3);
How am I getting different results from last two print statements? The first one behaves the way I expect, but the second one doesn't.
You're getting confused by the first printf only because dest is initialized with consecutive integers. Try
int dest[] = { 4, 72, 0, -5 };
instead.
Your real problem is operator precedence: *a + b parses as (*a) + b, not *(a + b) (the latter being equivalent to a[b]).
By the way, I'm not convinced
void *ptr = &dest;
*(int *)ptr
is legal. The standard says any (object) pointer can be converted to void * and back without loss of information, but here you're converting from type A to void * to type B (where A != B).
Specifically: &dest has type int (*)[4] (pointer to array of 4 ints), not int *. To fix this, do
void *ptr = dest;
instead. Or just int *ptr = dest;, then you don't even need to cast.
When you print the values:
printf("Before copy: %d, %d, %d, %d\n", *(int*)ptr, *(int*)ptr + 1, *(int*)ptr + 2, *(int*)ptr + 3);
You're not printing what you think you are. The expression *(int*)ptr + 1 takes ptr, converts it to an int *, then dereferences that pointer, which gives you the value of the first element, then adds 1 to that element's value. It does not add to the pointer value because the dereference operator * has higher precedence than the addition operator +.
You need to add parenthesis to get the behavior you want:
printf("Before copy: %d, %d, %d, %d\n", *(int *)ptr, *((int *)ptr + 1), *((int *)ptr + 2), *((int *)ptr + 3));
Related
So basically I'd like to sum two numbers and return their value while using a void function in C. I know this is easy peasy by using a normal function returning an int or a numeric type but I wanna work on my pointer knowledge.
I tried creating a pointer inside main() and then passing it as an argument to the void function. Then I calculated my sum in a new int variable and assigned the pointer to point to that specific variable. The problem is I can't "retrieve" it or "find" that area of memory in the main function.
Here's what I've tried:
void testFunction(int a,int b, int *x)
{
int c=a+b;
x=&c;
}
int main()
{
int n1=7;
int n2=90;
int *pointerParam;
testFunction(n1, n2, pointerParam);
printf("Value of pointer is %d\n", *pointerParam);
}
It just exits with an error code, it does nothing. If I try to printf *x inside the function, it does work so I know that part at least works.
Any help would be greatly appreciated!
There are multiple problems with the code as it is shown.
The main problem is probably that you misunderstand how emulation of pass-by-reference works in C.
For it to work you need to pass a pointer to the variable that should be set. This is done using the pointer-to operator &. You also need to dereference the pointer, to set the variable the pointer is pointing to.
Putting it together your program should look something like this (simplified):
void testFunction(int a,int b, int *x)
{
// Assign to where `x` is pointing
*x = a + b;
}
int main(void)
{
int n1 = 7;
int n2 = 90;
int result; // Where the result should be written
// Pass a pointer to the `result` variable, so the function can write to it
testFunction(n1, n2, &result);
}
I will show you a program that is no more than a set of printf() and your function. Maybe the program's output helps in showing these pointers, arrays and integers things.
The example
Consider these variables
int n[4] = {10, 20, -30, -40};
int v1 = 0;
int v2 = 0;
int* a_pointer = NULL;
int* is a pointer to an int, that's the meaning of the asterisk in the declaration. In this context the asterisk is called the dereference operator or the indirection operator. But the asterisk also is the multiplication operator in C. ;)
Now a_pointer points to nothing, the meaning of the NULL.
But a_pointer is there to hold an address of something, of an int. The way of getting such address of something is the address of operator, the &, that also has an alternate life as the bitwise and operator in C. Things of life.
In printf() the %p specifier shows an address. This
printf("\naddress of v1 is %p\n", &v1);
printf("address of v2 is %p\n", &v2);
printf("address of array n[0] is %p\n", n);
printf("address of array n[0] is %p\n", 1 + n);
printf("address of array n[0] is %p\n", 2 + n);
printf("address of array n[0] is %p\n\n", 3 + n);
shows (in a 32-bits compilation)
address of v1 is 008FFDA0
address of v2 is 008FFD9C
address of array n[0] is 008FFDA4
address of array n[1] is 008FFDA8
address of array n[2] is 008FFDAC
address of array n[3] is 008FFDB0
And you will see the reason the program prints these lines in the code below...
This line
a_pointer = &v1;
takes the address of v1 and assign it to the pointer a_pointer.
Now a_pointer is pointing to something, to v1, and you can use it in your function. These lines are equivalent
testFunction(n[0], n[3], &v1);
and
testFunction(n[0], n[3], a_pointer);
In these lines
testFunction(n[0], n[3], &v1);
printf("n[0] = %d, n[3] = %d, sum in v1 is %d\n", n[0], n[3], v1);
printf(
"p points to v1. value is %4d, address is %p\n\n", *a_pointer,
a_pointer);
you see the use of the pointer to access the value it points to, using the dereference operator in the printf().
Follow the program along to see a few uses of this.
In particular, see these lines
a_pointer = n + 3;
printf(
"\np points now to n[3]. value is %4d, address is %p\n",
*a_pointer, a_pointer);
to see the thing C is made for: address memory easily. n is int[4], an array of int. a_pointer is a pointer to int. And the language knows that when you write a_pointer = n + 3 that it needs to add to the address of n, an int[], the size of 3 int variables, and assign it to the pointer, so *a_pointer is n[3]and it is used to call testFunction() in
testFunction(n[1], n[2], n + 3);
program output
n[] is [10,20,-30,-40], v1 is 0 v2 is 0
address of v1 is 00CFFA9C
address of v2 is 00CFFA98
address of array n[0] is 00CFFAA0
address of array n[1] is 00CFFAA4
address of array n[2] is 00CFFAA8
address of array n[3] is 00CFFAAC
n[0] = 10, n[3] = -40, sum in v1 is -30
p points to v1. value is -30, address is 00CFFA9C
p now points to v2. value is 0, address is 00CFFA98
n[0] = 10, n[1] = 20, sum in v2 is 30
n[] is [10,20,-30,-40], v1 is -30 v2 is 30
p now points to v1. value is -30, address is 00CFFA9C
n[] is [10,20,-30,-40], v1 is -30 v2 is 30
now makes n[3] = n[1] + n[2] using testFunction()
n[] is [10,20,-30,-10], v1 is -30 v2 is 30
p points now to n[3]. value is -10, address is 00CFFAAC
the code
#include <stdio.h>
show(int[4], int, int);
void testFunction(int, int, int*);
int main(void)
{
int n[4] = {10, 20, -30, -40};
int v1 = 0;
int v2 = 0;
int* a_pointer = NULL;
show(n, v1, v2);
printf("\naddress of v1 is %p\n", &v1);
printf("address of v2 is %p\n", &v2);
printf("address of array n[0] is %p\n", n);
printf("address of array n[1] is %p\n", 1 + n);
printf("address of array n[2] is %p\n", 2 + n);
printf("address of array n[3] is %p\n\n", 3 + n);
a_pointer = &v1;
testFunction(n[0], n[3], &v1);
printf("n[0] = %d, n[3] = %d, sum in v1 is %d\n", n[0], n[3], v1);
printf(
"p points to v1. value is %4d, address is %p\n\n", *a_pointer,
a_pointer);
a_pointer = &v2;
printf(
"p now points to v2. value is %4d, address is %p\n", *a_pointer,
a_pointer);
testFunction(n[0], n[1], &v2);
printf("n[0] = %d, n[1] = %d, sum in v2 is %d\n", n[0], n[1], v2);
show(n, v1, v2);
a_pointer = &v1;
printf(
"\np now points to v1. value is %4d, address is %p\n", *a_pointer,
a_pointer);
show(n, v1, v2);
printf("\nnow makes n[3] = n[1] + n[2] using testFunction()\n");
testFunction(n[1], n[2], n + 3);
show(n, v1, v2);
a_pointer = n + 3;
printf(
"\np points now to n[3]. value is %4d, address is %p\n",
*a_pointer, a_pointer);
return 0;
};
show(int n[4], int v1, int v2)
{
printf(
"n[] is [%d,%d,%d,%d], v1 is %d v2 is %d\n", n[0], n[1], n[2],
n[3], v1, v2);
};
void testFunction(int a, int b, int* sum)
{
*sum = a + b;
return;
}
I will not go into religious discussions here, but you may find easier to understand the meaning of the declarions if you write
int* some_int = NULL;
instead of
int *some_int = NULL;
you declare a name, and the name is some_int. The compiler will tell you that some_int is int*, its type. The fact that *some_int is an int is a consequence of the application of an operator to a variable.
You lacked just to understand how pointers are managed, but you were almost correct:
/* this is almost correct, you could have just said: *x = a + b; */
void testFunction(int a,int b, int *x)
{
int c=a+b;
*x=c; /* the pointed to value is what we are assigning */
}
int main()
{
int n1=7;
int n2=90;
int result; /* vvvvvvv this is the important point */
testFunction(n1, n2, &result); /* you pass the address of result as the required pointer */
printf("Value of pointer is %d\n", result);
}
I have a doubt regarding pointer of pointer arithmetic in C.
If we do
int ** ptr = 0x0;
printf("%p",ptr+=1);
The output will be ptr+(# of bytes needed for storing a pointer, in my case 8).
Now if we declare a matrix:
int A[100][50];
A[0] is a pointer of pointer.
A[0]+1 will now point to A[0]+(# of bytes needed for storing an integer, in my case 4).
Why "normally" 8 bytes are added and now 4?
A[0]+1 will point to A[0][1], so it is useful, but how does it work?
Thank you!
Consider this program, run on a 64-bit machine (a Mac running macOS Mojave 10.14.6, with GCC 9.2.0 to be precise):
#include <stdio.h>
int main(void)
{
int A[100][50];
printf("Size of void * = %zu and size of int = %zu\n", sizeof(void *), sizeof(int));
printf("Given 'int A[100][50];\n");
printf("Size of A = %zu\n", sizeof(A));
printf("Size of A[0] = %zu\n", sizeof(A[0]));
printf("Size of A[0][0] = %zu\n", sizeof(A[0][0]));
putchar('\n');
printf("Address of A[0] = %p\n", (void *)A[0]);
printf("Address of A[0] + 0 = %p\n", (void *)(A[0] + 0));
printf("Address of A[0] + 1 = %p\n", (void *)(A[0] + 1));
printf("Difference = %td\n", (void *)(A[0] + 1) - (void *)(A[0] + 0));
putchar('\n');
printf("Address of &A[0] = %p\n", (void *)&A[0]);
printf("Address of &A[0] + 0 = %p\n", (void *)(&A[0] + 0));
printf("Address of &A[0] + 1 = %p\n", (void *)(&A[0] + 1));
printf("Difference = %td\n", (void *)(&A[0] + 1) - (void *)(&A[0] + 0));
return 0;
}
The output is:
Size of void * = 8 and size of int = 4
Given 'int A[100][50];
Size of A = 20000
Size of A[0] = 200
Size of A[0][0] = 4
Address of A[0] = 0x7ffee5b005e0
Address of A[0] + 0 = 0x7ffee5b005e0
Address of A[0] + 1 = 0x7ffee5b005e4
Difference = 4
Address of &A[0] = 0x7ffee5b005e0
Address of &A[0] + 0 = 0x7ffee5b005e0
Address of &A[0] + 1 = 0x7ffee5b006a8
Difference = 200
Therefore, it is possible to deduce that A[0] is an array of 50 int — it is not a 'pointer of pointer'. Nevertheless, when used in an expression such as A[0] + 1, it 'decays' into a 'pointer to int' (pointer to the type of the element of the array), and hence A[0] + 1 is one integer's worth further through the array.
The last block of output shows that the address of an array has a different type — int (*)[50] in the case of A[0].
I'm running this program:
#include<stdio.h>
void main(){
int num = 1025;
int *poinTer = #
char *pointChar = poinTer+1;
*pointChar = 'A';
printf("Size of Integer: %d\n", sizeof(int));
printf("Address: %d, Value: %d\n", poinTer, *poinTer);
printf("Address: %d, Value: %c\n", poinTer+1, *(poinTer+1));
printf("Address: %d, Value: %c\n", pointChar, *pointChar);
}
*pointChar and *(poinTer+1) should output same result but the output that I'm getting is different. *pointChar is not outputting any value:
Size of Integer: 4
Address: 1704004844, Value: 1025
Address: 1704004848, Value: A
Address: 1704004673, Value:
What's happening here?
When you perform + 1 on a pointer, it does not necessarily increase the memory address by 1. It increases it by sizeof(*ptr).
In this case, poinTer + 1 is equivalent to (char*)poinTer + sizeof(int). This actually makes dealing with arrays much easier.
The good old fashioned ptr[i] is syntactic sugar for *(ptr + i). So, if you have an array of 10 integers, ptr[4] will point to the 5th element rather than 4 bytes away from the base address (since integers are generally 4 or 8 bytes).
So what you've actually done is:
Create an int (num) on the stack and gave it the value 1025
Created a int*(poinTer) on the stack and assigned it the memory address of num
Incremented the pointer by sizeof(int) (which unintentionally points to a different memory address), then cast it to a char* and assigned it to a new pointer.
Assigned the byte pointed to at this new memory address the value 65 ('A').
This is probably what you wanted to do:
#include<stdio.h>
void main(){
int num = 1025;
int *poinTer = #
char *pointChar = (char*)poinTer + 1;
*pointChar = 'A';
printf("Size of Integer: %d\n", sizeof(int));
printf("Address: %d, Value: %d\n", poinTer, *poinTer);
printf("Address: %d, Value: %c\n", (char*)poinTer + 1, *((char*)poinTer+1));
printf("Address: %d, Value: %c\n", pointChar, *pointChar);
}
I am trying to wrap my head around "pointer to a pointer". And I tried some experiments and I got stuck here for a while:
int array[5] = {4 , 5 ,6 ,7 ,8};
int *p = array;
int **pp = &p;
for ( int i = 0; i < 4; i ++)
{
printf("\nprinting\n");
printf("Source: %d\n", array[i]);
printf("Output by pointer: %d, %d\n", p[i], *(p + i));
printf("Output by pointer to a pointer: %d, %d\n", *pp[i], **(pp + i) );
}
And I got this as output:
printing
Source: 4
Output by pointer: 4, 4
Output by pointer to a pointer: 4, 4
printing
Source: 5
Output by pointer: 5, 5
I don't understand why after 1 loop, the program stop at the 2nd loop- line 9. Did I misunderstand anything basic knowledge or something else.
Thank you for reading.
Change the last printf to:
printf("Output by pointer to a pointer: %d, %d\n", (*pp)[i], *(*pp + i) );
You're basically using *pp in place of p, but the * operator doesn't group as tightly as [] so you need to use parentheses in the first form. In the second form, you need to dereference pp before adding i, after which the result is dereferenced.
For starters it is unclear why there is used the magic number 4 in the loop instead of the number 5 that is the number of elements in the array
for ( int i = 0; i < 4; i ++)
^^^^^
The pointer pp does not point to first element of an array. It points to a single object
int **pp = &p;
So these expressions
*pp[i] (that is equivalent to *(pp[i] )
and
**(pp + i)
does not make sense.
An expression using the pointer p can be written using the pointer pp like *pp.
So these correct expressions
p[i]
and
*(p + i)
can be written using the pointer pp the following way (just substitute p for *pp taking into account operation precedences)
( *pp )[i]
and
*( *pp + i )
You acesses to pointer thru pointer-to-pointers are wrong:
you must access the pointee as the array:
int array[5] = {4 , 5 ,6 ,7 ,8};
int *p = array;
int **pp = &p;
for ( int i = 0; i < 4; i ++)
{
printf("\nprinting\n");
printf("Source: %d\n", array[i]);
printf("Output by pointer: %d, %d\n", p[i], *(p + i));
printf("Output by pointer to a pointer: %d, %d\n", (*pp)[i], *(*pp + i) );
}
This line is wrong
printf("Output by pointer to a pointer: %d, %d\n", *pp[i], **(pp + i) );
You need to change it to
printf("Output by pointer to a pointer: %d, %d\n", (*pp)[i], *(*pp + i) );
so that you dereference the double pointer before using it as a normal pointer.
You can think of it like this:
p is the same as (*pp)
In other words - in a valid expression that uses p you are allowed to substitute p with (*pp). That is
p[i] --> (*p)[i]
*(p + i) --> *((*pp) + i) --> *(*pp + i)
Notice that the parenthesis is important. The parenthesis can be removed in the second example but not in the first as [] has higher precedence than *.
Doing pp + i generates a pointer that doesn't point to any valid object. So when you dereference it using **(pp + i) you do an illegal access an your program crashes.
From what I understand, blocks of allocated memory is continuous, so addresses in an array are sequential in multiples of the size of the array data (int = 4 on some systems, etc.)
I've also seen that for an array A and index i, A[i] == *(A+i) in C.
A 2D array is like an array of arrays, so I wanted to know how to determine the expression for an N-dimensional array if I was crazy enough not to use the [] operator.
If the array was created with pointers, wouldn't it be necessary to know the length of the level?
For
int array2d[X][Y];
the two expressions are equivalent:
array[1][2];
*((int *)array + 1*Y + 2);
For
int array3d[X][Y][Z]
the two expressions are equivalent:
array[1][2][3];
*((int *)arr + 1*Y*Z + 2*Z + 3);
So, for
int arraynd[X][Y][Z]..[N]
the two expression are equivalent:
arraynd[1][2][3]...[n];
((int *)array + 1*X*Y*Z*...*N + 2*Y*Z*...*N + 3*Z*...*N + ... + n);
Suppose you declare int a[m][n]; If you reference a[i][j], it is equivalent to (a[i])[j] which, as you noted, is equivalent to (*(a+i))[j], which is equivalent to *((*(a+i))+j). In terms of bytes, the integer is scaled by the size of the object pointed to, so i is scaled by the size of a[0], or *a, which is the size of the sub-array, which is sizeof(int) * n. The dereference of the result, via the * operator, is essentially a type cast, converting it from a pointer to the sub-array, type int (*)[n], to a pointer to an element of the sub-array, type int *. Then, when adding j, it is scaled by sizeof(int). The outer dereference, via the * operator, actually dereferences the pointer, either reading the value or modifying it, depending on the context.
Edit: Here's a simple demonstration program you can try. It illustrates what I explained:
#include <stdio.h>
int main()
{
int a[5][10];
printf("%d %d %d\n", sizeof(int[5][10]), sizeof(int[10]), sizeof(int));
printf("%d %d %d\n", sizeof(a), sizeof(a[0]), sizeof(a[0][0]));
printf("%d %d %d\n", sizeof(a), sizeof(*a), sizeof(**a));
void *p1 = a;
void *p2 = a + 1;
void *p3 = *(a + 1) + 3;
printf("%d %d\n", (int) (p2 - p1), (int) (p3 - p2));
printf("%d %d\n", 1 * (sizeof(int) * 10), 3 * sizeof(int));
return 0;
}