In Visual Studio 2019, I tried to assign value to int pointer at specified position, but it doesn't work. Is this possible?
Moreover how I can printf a pointer's value, and not the address?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p =(int*)calloc(10,1);
p[0]=1;
p[1]=0;
p[2]=1;
printf("%d\n",p);
}
Thank
calloc(10,1) allocates 10 single byte items not 10 integers. So (except 8 bits uCs where int is 2 bytes) your allocated memory area is far too short. if you want to allocate space for 10 integers you need to int *p = calloc(10, sizeof(*p));
printf("%d", p) invokes an UB as p is the reference (address) stored in the pointer p. You need to dereference the pointer to get the integer referenced (pointed) by the p pointer printf("%d\n, *p);
To print the reference stored in the pointer you need to use the correct format: printf("%p\n", (void *)p);.
It works.
To print the value you need to derreference with * or index with [].
printf("%d\n",*p); //p[0]
printf("%d\n", p[0]); //p[0]
printf("%d\n",*(p + 1)); //p[1]
printf("%d\n", p[1]); //p[1]
Related
Using DevCpp with TDM GCC 4.9.2 on Windows 8. But I don't think the platform matters for this question.
I know that we can use a pointer to point to a single data or an array of data.
I have learned about pointer to arrays but never used it. What advantage does one have over the other?
Sample Code...
#include <stdio.h>
int main()
{
int x[2]={10,20};
int *p1= NULL; //simple pointer
int (*p2)[] = NULL; //pointer to an array, specifically
p1 = x;
p2 = &x; //removing the & gives me a warning of "assignment from incompatible pointer types".
printf("x[1] = %d\n", x[1]);
*(p1+1) = 7;
printf("x[1] = %d\n", x[1]);
(*p2)[1] = 55;
printf("x[1] = %d", x[1]);
return 0;
}
Does p1 or p2 have an advantage over the other?
They are completely different.
int *p; - is the pointer to the int
int (*p)[1]; is a pointer to the array (in this case one element only)
In your trivial example the pointer arithmetic will be the same and generated code will be the same. But they still have different types and you may get warnings when compiled.
The "advantages" you will see when your example will be less trivial:
int (*p)[100];
p++; the pointer will point to the next 100 elements int array.
Pointer to an array means a pointer which accepts address of an array.
let's say array is int arr[5],in which size of int is 4 byte.
p is a pointer to an array that accept the address of an int array.
int arr[5];
int (*p)[5];
p=&arr;//address of an array block
let's say the base address is 1000 .So after increment in p it will lead us to 1020 address,because the size of the array block is 20 bytes.
p points to 1000 address
p++;
//Now p points to 1020 not 1004.
Whereas in case of int *q, q will point to 1004 as usual.
I have some code that looks like this:
int *array[10];
printf("%p\n", array); // Prints an address
printf("%p\n", *array); // Prints a different address
printf("%d\n", **array); // Segmentation Fault 11
printf("%d\n", *array[0]); // Segmentation Fault 11
printf("%d\n", (*array)[0]); // Segmentation Fault 11
Why do I get a segmentation fault? Shouldn't it print the first value in the first array?
To take a closer look, understand the nature of the declaration:
int *array[10];
This declares an array of 10 pointers (currently uninitialized) to ints -- note that this is not the same as a pointer to an array of 10 ints, which would instead be declared int (*array)[10]. Even declared this way though, you'd still need to initialize the pointer with something.
printf("%d\n", array); // Prints an address
This prints an the address of the ages array (the array is converted to a pointer automatically by passing it to printf).
printf("%d\n", *array); // Prints a different address
This uses the same rules to convert the array to a pointer, and then dereferences that pointer. Therefore, you're printing the first value of the array (equivalent to printf("%d\n", ages[0])). However, what you're actually printing here is an address, not an integer (even if it is uninitialized).
printf("%d\n", **array); // Segmentation Fault 11
printf("%d\n", *array[0]); // Segmentation Fault 11
printf("%d\n", (*array)[0]); // Segmentation Fault 11
Each of these are now dereferencing the uninitialized pointer stored in array[0]. They do indeed be refer to an int, but the pointer to that int is whatever the compiler and/or your OS decided to put in there.
Example: Pointer to an array
An example of using a pointer to an array looks like this:
#include <stdio.h>
int main()
{
int array[10] = { 1,2,3,4,5,6,7,8,9,10 };
int (*parr)[10] = &array;
printf("%p\n", parr);
printf("%p\n", *parr);
printf("%d\n", **parr);
printf("%d\n", *parr[0]);
printf("%d\n", (*parr)[0]);
}
Output (addresses vary, obviously)
0x7fff5fbff990
0x7fff5fbff990
1
1
1
The last three all ultimately lead to the same element, but go about it in different ways.
You get a segmentation fault because you are attempting to dereference an uninitialized pointer, which is Undefined Behavior.
This command (and all following):
**ages
Dereferences the array (which decays to a pointer), which you then dereference. You have an array of pointers, not a pointer to an array.
int *array[10];
array is array[10] of pointer to int (note that [] has higher precedence than *). But none of these 10 pointers have been initialised to point to valid location.
Given that,
printf("%d\n", array); // address of array itself (also address of first element)
printf("%d\n", *array); // getting the value of the fisrt array element - UB/unitilialise (currently points to some random location)
printf("%d\n", **array); // dereference that first pointer - UB/segfault as deferencing an initialised pointer
printf("%d\n", *array[0]); // same as *array
printf("%d\n", (*array)[0]); // same as **array
#include <iostream>
using namespace std;
#include <math.h>
#include <string.h>
int main() {
int arr[5] = {1,2,3,4,5};
int *p=arr;
int intgerSize=sizeof(int);
for(int k=0;k<5;k++)
{
cout<<"arr ["<<k<<"] "<<*(p+(k*sizeof(int)/intgerSize));
cout<<" "<<(p+(k*sizeof(int)/intgerSize));
cout<<" "<<p+k<<"\n";
}`enter code here`
return 0;
}
OUTPUT:-
arr [0] 1 0x7ffd180f5800 0x7ffd180f5800
arr [1] 2 0x7ffd180f5804 0x7ffd180f5804
arr [2] 3 0x7ffd180f5808 0x7ffd180f5808
arr [3] 4 0x7ffd180f580c 0x7ffd180f580c
arr [4] 5 0x7ffd180f5810 0x7ffd180f5810
Why does the pointer p always point to its own memory address as an integer in the following example. I can't see where it is initialized and would guess that it would be a garbage value. Can someone show me why it is not a garbage value. By the way I am compiling this in gcc with -std set to c99.
#include <stdio.h>
int main() {
int *p; int a = 4;
p = &a;
*p++;
printf("%d %u\n", *p, p);
}
Your problem (as the other answers point out) is with *p++;. What that says to do is dereference p then increment the address in p.
From what you are seeing, we can assume p comes directly after a in memory
_________________________________________
|something | a | p | something else |
-----------------------------------------
So what ends up happening is p points to a, then is incremented so it points to itself (or more specifically: p stores the address that p is at).
First you need to print a pointer value with %p, and your code has undefined behavior. You move the pointer one place after a and dereference it.
Your code doesn't illustrate the point you (it seems) wanted, the following will:
#include <stdio.h>
int main() {
int *p; int a = 4;
p = &a;
printf("%d %p %p\n", *p, p, &p);
}
It produces something like:
4 0x7fff5c17da44 0x7fff5c17da48
p points to a then *p is the value of a. The value of p is 0x7fff5c17da44 which is the adresse of a and the address of p (&p) is 0x7fff5c17da48.
I am a total beginner to C so please, work with my ignorance. Why does a normal pointer
int* ptr = &a; has two spaces in memory (one for the pointer variable and one for the value it points to) and an array pointer int a[] = {5}; only has one memory space (if I print out
printf("\n%p\n", a) I get the same address as if I printed out: printf("\n%p\n", &a).
The question is, shouldn't there be a memory space for the pointer variable a and one for its value which points to the first array element? It does it with the regular pointer int* ptr = &a;
It's a little unclear from your question (and assuming no compiler optimization), but if you first declare a variable and then a pointer to that variable,
int a = 4;
int *p = &a;
then you have two different variables, it makes sense that there are two memory slots. You might change p to point to something else, and still want to refer to a later
int a = 4;
int b = 5;
int *p = &a; // p points to a
// ...
p = &b; // now p points to b
a = 6; // but you can still use a
The array declaration just allocates memory on the stack. If you wanted to do the same with a pointer, on the heap, you would use something like malloc or calloc (or new in c++)
int *p = (int*)malloc(1 * sizeof(int));
*p = 4;
but of course remember to free it later (delete in c++)
free(p);
p = 0;
The main misunderstanding here is that &a return not pointer to pointer as it expected that's because in C language there some difference between [] and * (Explanation here: Difference between [] and *)
If you try to &a if a was an pointer (e.g. int *a) then you obtain a new memory place but when your use a static array (i.e. int a[]) then it return address of the first array element. I'll also try to clarify this by mean of the next code block.
#include <stdio.h>
int main(int argc, char *argv[])
{
// for cycles
int k;
printf("That is a pointer case:\n");
// Allocate memory for 4 bytes (one int is four bytes on x86 platform,
// can be differ for microcontroller e.g.)
int c = 0xDEADBEEF;
unsigned char *b = (unsigned char*) &c;
printf("Value c: %p\n", c);
printf("Pointer to c: %p\n", &c);
printf("Pointer b (eq. to c): %p\n", b);
// Reverse order (little-endian in case of x86)
for (k = 0; k < 4; k++)
printf("b[%d] = 0x%02X\n", k, b[k]);
// MAIN DIFFERENCE HERE: (see below)
unsigned char **p_b = &b;
// And now if we use & one more we obtain pointer to the pointer
// 0xDEADBEEF <-- b <-- &p_b
// This pointer different then b itself
printf("Pointer to the pointer b: %p\n", p_b);
printf("\nOther case, now we use array that defined by []:\n");
int a[] = {5,1};
int *ptr = &a;
// 'a' is array but physically it also pointer to location
// logically it's treat differ other then real pointer
printf("'a' is array: %x\n", a);
// MAIN DIFFERENCE HERE: we obtain not a pointer to pointer
printf("Pointer to 'a' result also 'a'%x\n", &a);
printf("Same as 'a': %x\n", ptr);
printf("Access to memory that 'a' pointes to: \n%x\n", *a);
return 0;
}
This is very simple. In first case,
int* ptr = &a;
you have one variable a already declared and hence present in memory. Now you declare another variable ptr (to hold the address, in C variables which hold address of another variable are called pointers), which again requires memory in the same way as a required.
In second case,
int a[] = {5};
You just declare one variable (which will hold a collection of ints), hence memory is allocated accordingly for a[].
In this expression, int* p = &a; p has only one memory location, of the WORD size of your CPU, most probably, and it is to store the address (memory location) of another variable.
When you do *p you are dereferencing p, which means you are getting the value of what p points to. In this particular case that would be the value of a. a has its own location in memory, and p only points to it, but does not itself store as content.
When you have an array, like int a[] = {5};, you have a series (or one) of memory locations, and they are filled with values. These are actual locations.
Arrays in C can decay to a pointer, so when you printf like you did with your array, you get the same address, whether you do a or &a. This is because of array to pointer decay.
a is still the same location, and is only that location. &a actually returns a pointer to a, but that pointer sits else where in memory. If you did int* b = &a; then b here would not have the same location as a, however, it would point to a.
ptr is a variable containing a memory address. You can assign various memory addresses to ptr. a is a constant representing a fixed memory address of the first element of the array. As such you can do:
ptr = a;
but not
a = ptr;
Pointers point to an area in memory. Pointers to int point to an area large enough to hold a value of int type.
If you have an array of int and make a pointer point to the array first element
int array[42];
int *p = array;
the pointer still points to a space wide enough for an int.
On the other hand, if you make a different pointer point to the whole array, this new pointer points to a larger area that starts at the same address
int (*q)[42]; // q is a pointer to an array of 42 ints
q = &array;
the address of both p and q is the same, but they point to differently sized areas.
This question already has answers here:
How come an array's address is equal to its value in C?
(6 answers)
Closed 9 years ago.
I tried a code to see what is the difference between &i and i if i is an array. My assumption was that i represents the starting address of the array, and I had no idea what will happen if I print &i as well.
The result was surprising (to me), as both i and &i was the starting address of the array.
#include<stdio.h>
int main()
{
char str[25] = "IndiaBIX";
int i[] = {1,2,3,4};
printf("%i\n", &i);
printf("%i\n", i);
return 0;
}
The result will be:
2686692
2686692
This is the same address.
But if I use a pointer to int:
#include<stdio.h>
#include <stdlib.h>
int main()
{
int *j = (int *) malloc(sizeof(int));
*j = 12;
printf("%i %i %i\n", *j,j,&j);
return 0;
}
The result will be:
12
5582744
2686748
Here I assume the first is the value of the memory area pointed to by j,the second is the address of the memory area pointed to by j, the third is the memory address of the pointer itself. If I print i and &i, why does &i not mean the memory address of the pointer i?
int i[] = {1,2,3,4};
The difference is their type, i has a type of integer array, &i has a type of a pointer of an integer array.
Yeah, both i and &i leads to print the same answer but they are not exactly same,
-> i represents the address of the first element in an array named i.
-> &i represents the address of the whole array(though values of both are same, their types are different)
For more info, please refer this [link]http://publications.gbdirect.co.uk/c_book/chapter5/arrays_and_address_of.html
int ar[10];
ip = ar; /* address of first element */
ip = &ar[0]; /* address of first element */
ar10i = &ar; /* address of whole array */