Programming C: Posts 11 – Pointers in c
Content
1. Introduction pointers in C
The variables we have known and used in the past are variable in size and data type identified. They call this type variables are static variables. When you declare a static variable, a memory cell for the variable amount will be allocated without knowing during program execution using all of its memory cells or not. On the other hand, This form of static variables will exist during program execution, despite the changes that the program uses only 1 disposable.
Some restrictions may encounter when using static variables:
- Allocate memory cell balance, cause wasted memory cells.
- Allocate memory cells lacking, program execution error.
To avoid the limitations on, C language provides us with a special variable called volatility with the following characteristics:
- Only arise during program execution, not arising at the start program.
- When running the program, the size of the variable, memory and memory address is allocated to the variable may change.
- After you finish using it can liberation to save space in memory. However, the variation does not address certain I will not be able to access them. Therefore, C language provides us with a special kind of variable again to overcome this, pointer variable that is (pointer) with the characteristics:
- Pointer variable does not contain data that contain the address of the data or contains the address of the memory containing data.
- The size of the pointer does not depend on the type of data.
2. Pointer
Each variable is declared to have been allocated to 1 certain memory areas where (address) different. Pointer variable used to store the address of the variable.
2.1 Example
// e.g about pointer - code by nguyenvanquan7826 #include <stdio.h> int main() { /* khai bao bien x va bien con tro px */ int x, *px; px = &x; /* &x : tra ve dia chi cua bien x * px = &x : gan dia chi cua bien x cho px hay px tro den x */ x = 42; printf("Vi tri cua bien x la %p \n", &x); printf("Noi dung cua bien x la %d \n", x); printf("Vi tri cua bien x la %p \n", px); printf("Noi dung cua bien x la %d \n", *px); *px = 7826; printf("\n -------- \n\n"); printf("Noi dung cua bien x la %d \n", x); printf("Noi dung cua bien x la %d \n", *px); return 0; }
Result:
Result:
The record x la 42
Vi tri cua well x 0x7ffe064348fc
The record x la 42
--------
The record x la 7826
The record x la 7826
Through this opening example we can draw the following points:
the. Declare cursor variables
For each type of data we have respectively a pointer variable of that type.
Type * Name pointer;
In the above example we declare 1 pointer variable of type int px.
b. Regulation of pointers that point to the
We use the operator & for address 1 variable and then assign that address pointer.
Name pointer = &variable;
c. How to access
With the cursor px above have 2 Though the permit is:
- px : Get the address to which it kept (point to)
- *px : Get the value of the memory that it points to.
In the example above we can see that after the assignment px = &x; then we write the:
- px would be equivalent to &x
- *px is equivalent to x. and can be used in the calculations * px, expression.
d. Some operations on pointer
// e.g about pointer - code by nguyenvanquan7826 #include <stdio.h> int main() { /* khai bao bien x va 2 bien con tro px, qx */ int x, *px, *qx; px = &x; printf("Nhap gia tri cho vung nho px tro toi: "); scanf("%d", px); /* px la con tro nen khong viet scanf("%d", &px); */ qx = px; /* gan gia tri cua px cho qx, qx cun tro toi x*/ printf("Vi tri cua bien x la %p \n", &x); printf("Vi tri cua bien x la %p \n", px); printf("Vi tri cua bien x la %p \n", qx); printf("Noi dung cua bien x la %d \n", x); printf("Noi dung cua bien x la %d \n", *px); printf("Noi dung cua bien x la %d \n", *qx); // tang gia tri cua o nho len, <=> x = x + 7826 *px += 7826; printf("Noi dung cua bien x la %d \n", x); px++; /* cong them mot don vi cho px * => px tro toi vung nho tiep theo */ printf("Vi tri px tro toi la %p \n", px); return 0; }
Result:
Enter a value for the cove px ash toi: 42
Vi tri well cua x 0xbfba58a0
Vi tri well cua x 0xbfba58a0
Vi tri well cua x 0xbfba58a0
The record x la 42
The record x la 42
The record x la 42
The record x la 7868
Vi tro sort px thee 0xbfba58a4
For eg we saw on some operations on pointers common after: (in addition to many other operations).
- 2 pointer variable of the same type can be assigned to each other or perform public accounting for an integer, minus 2 pointers for each. In the example above we perform calculations:
- Assign: q x = px; When it receives the value of px qx is the address of the variable x, ie px and qx and pointing to x. In addition we can assign the following: q x = px + 2; with qx, px is the same pointer type. Subtraction 2 pointer of the same type will return 1 integer values (int). This is the distance (Some elements) between 2 including pointers
- Increase: The permit to increase or decrease, subtraction is performed on the same pointer arithmetic variables. The only difference is that it rises and falls, plus or minus according to the type of single byte that it has.
CEO. In the above example it is possible to increase: px ; When assuming this is pointing to the address px: 0xbfba58a0, then allowed to increase its value is (point to the location) 0xbfba58a4 (increase 4) because px is that each pointer variable of type int int accounts 4 byte in memory. - In addition we are allowed to change the value of the variable x by * px math = 3; In essence this operation was to change the value in the memory (address) that px points to, which led to the value of the variable x is changed according to.
Have you noticed:
- Depending on the compiler or the operating system that is the capacity of different types. (This is the translation of type int accounts 4 byte, but in the other services it occupies 2 byte). For each type of storage you use sizeof() but in all 2 mentioned.
- Also, depending on the operating system each pointer variable, no matter what type of cursor (int, float, double,...) also accounts for the same number of bytes. Operating system 32 bit the pointer variable accounting 4 byte, operating system 64 bit the pointer variable accounting 8 byte.
3. Allocate and recover memory
the. Allocation:
Prior to this one small example.
// e.g about pointer - code by nguyenvanquan7826 #include <stdio.h> int main() { int *px; *px = 42; printf("Vi tri con tro px la %p \n", px); printf("Gia tri con tro px tro toi la %d \n", *px); return 0; }
When compiled, it will not benefit (warning), when run will not be able to run that program will back out.
The reason is that when the cursor variable declaration px the new machine only provide 2 byte to store the address of the pointer variable that has not allocate memory for the pointer data storage px. (similar cooperative supply 2 Kg of rice for you to do the same but does not give you the land to you that plated ring ).
Noted: There are a number of compiler error but still will not run normally, but the best is that we should allocate Use. This error appears most clearly when you use the pointer to the array which we will discuss in later.
Well we went on key issues, how to allocate memory for pointers.
To allocate memory for pointers we use the following function in the library stdlib.h.
- malloc : cursor name = (pointer type *) malloc (sizeof(pointer type));
- calloc : cursor name = (pointer type *) malloc (n, sizeof(pointer type));
In that sizeof(pointer type) the size of the type; n is the number of sizeof(pointer type) granted.
// e.g about pointer - code by nguyenvanquan7826 #include <stdio.h> #include <stdlib.h> int main() { int *px, *qx; px = (int *) malloc(sizeof(int)); qx = (int *) calloc(1, sizeof(int)); printf("Vi tri con tro px la %p \n", px); printf("Gia tri con tro px tro toi la %d \n", *px); printf("Vi tri con tro qx la %p \n", qx); printf("Gia tri con tro qx tro toi la %d \n", *qx); return 0; }
Here you note: The only difference between malloc and calloc that you simply understand when allocated with malloc allocates the machine px 1 cell any cell without knowing what data is or no data (* px so valuable as above) calloc, too, but also other 1 Points are allocated after the machine will automatically assign values always 0 the memory cell that refers to the variable qx, News qx default value is 0.
When allocating the pointer 1 certain amount of memory cells during the process of work we lack and need to allocate more, we use the command realloc:
cursor name = (pointer type *) realloc (cursor name, the amount allocated to * sizeof(pointer type));
In that: = amount allocated to old + new.
CEO: Initially we allocated the pointer is px 10 memory cells.
Then it wants to allocate more 5 more memory cells, the amount allocated = 15.
b. Recovery and check the remaining memory
To recover the memory allocation functions we use free(cursor name);
3. The function of the cursor
As in all Permutation function in C we know how to pass parameters a,b in HoanVi function is passing by value, not by transmission by address (or parameters) so even though the value of the function variables were changed, but after the function is done, the value has yet to be changed. And we will be revised by passing parameters form a cursor and pointer b to the swap can be swapped at the address of the memory cells that. And when we get the desired result.
// e.g about pointer - code by nguyenvanquan7826 #include <stdio.h> void hoanVi(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } int main() { int a = 42, b = 7826; printf("Truoc khi goi ham hoan vi: a = %d, b = %d \n", a, b); hoanVi(&a, &b); printf("Sau khi goi ham hoan vi: a = %d, b = %d \n", a, b); return 0; }
you ask yourself . you have documentation or examples about pointers and arrays not. eg an array 10 cursor or pointer to array 10 element!
thank you
It was like carrying Cai 2 fin moves. Right before you write these incidents co bi xoa mat roi. Ban on bringing see bared heart
Vietnam allocates memory ,can use the command : pointer = new type dc ko him
Yes, but it is in C ++ you ah
the% p that is what you think
That is print the address of the variable
if you change int * int px &px different then not he. otherwise they helped him explain me sir ko DC
thank you!
when declaring int * px, it is 1 Declares structure pointer, and not have to declare int &px.
really. I see the initialization list who they declare such
void khoitao(DS A,int &n)
{
n=0;
}
he is right or wrong
Ah that is used in the function. When such declarations, it is like declaring * px is allowed to change the value of this variable when off function. But it is in C ++ and when this function call is not transmitted to the jaw that address just in severance variable transmission.
You can see this for example, to learn more:
https://www.cachhoc.net/2014/12/12/lap-trinh-c-bai-6-ham/#VD3_Ham_hoan_vi
why the provisions of pointers that point to areas that he.
This is for cursor control of a memory cell value then they point period…
Thank you
If y = * z such trog
y are variables
z la pointer
Au know help e with
What question do not understand you@@
#define PA_ODR *(unsigned char*)0x5000
the meaning of the question you asked on what is ordered ?
Defines a constant command
So I used the reference purposes (CEO: float tong(float &the ) as defined function to do what he
So after getting off function, the value of a possible change. For example, before entering a is 5, after entering a function, it is 9. After exiting a function still has value 9 but did not return 5.
Using the function returns 1 reference( CEO : int & myfunc() )để làm gì vậy anh.!!! .em tks . em thấy mấy sách khai báo như vậy nhưng ko hiểu nó dùng làm gì ?
Cái này mình cũng chịu. Chưa dùng thử bao giờ 😉
có thể cho e vd về sử dung con trỏ kết hợp vs struct ko 🙂
You try 2 bài này xem
https://www.cachhoc.net/2014/12/21/lap-trinh-c-bai-13-danh-sach-lien-ket-don-cai-bang-con-tro/
https://www.cachhoc.net/2014/12/19/lap-trinh-c-bai-11-kieu-cau-truc-struct/
A military school do so? Sn how much a right?
The first line 6 in the example 2 you give:
printf(“Enter a value for the cove px ash toi: “);
scanf(“%d”, px);
seemed to like this:
printf(“Enter a value for the cove px ash toi: “);
scanf(“%d”, *px);
You can explain to this site is not clever????
Because the cursor px px call always đk, it looks like &the. * Px is also referred to its value like calling a.
He asked me to check the size of the pointer is 2 How sir bite.
For example, check the size of int you use sizeof() . but when e Using sizeof(p) or sizeof(*p) not out 2 bite.
Hello.
In the article mentioned e find a pointer to the lack of memory cells in the process of working. A case can be for children but lack the memory pointers in the process of working is not it ? Plus he could say more about the role of n in function to help you get ko sir calloc ?
For example, we originally allocated to 100 memory cells, but due to the need to save the latter amount exceeds 100 is missing.
n is the number of cells need to allocate memory.
why in the first instance should not allocate memory that the first example 3 the need to allocate memory sir.
As in the previous example it is assigned directly then you.
Sao không có nút like vậy bạn
pdest = strstr( string, str );
result = (int)(pDEST – string + 1);
His brother nguyenvanquan7826 explained they obtained statements 2 Star returns tri dc micro lending by string str
psest is positioned at the star grape chuoi tru la ma dc string for each loan
e asked him for. E also want to create a blog site like a bit so that e kh how your article is as a medium with instructions had code in it. a can show e to be kh… e already know php , css, html , e want to compose all out and save to db finished then just load up thui that kh know how that can just write a post that had such illustrative code is…
You learn wordpress nhé. I'm using it.
You can ask yourself is accounted 2byte pointer to host memory address, but as for example the opening, the location of the variable x is 0xbff327e4, This number is greater than 2byte. I have not really understand this place, hope you answer their fears with
darling you could explain to me int * p1 =&x , int **p2 =&p1. it means how ko sir? int * p1 = and the&x it like int * p1 vs; p1 =&x no sir? I thank
It is assigned the address of x in pointer p1, address assignment p1 to p2 pointer. Post it similar ones nhé.
Waiter, in examples 2 allocation of part 2a I a, apparently he did not assign a value to * px, attention bottom part he has recorded * px valuable as above. E ask for the results of the program so that it comes out what he? And n in his calloc his hips properly randomized, and it have any impact if I run the program with bigger size n his hips. E thank you sir
I said that the program will error. Also n is the number you want, with 1 like the other pixels is n 1. If the test section, the array has n n is the number of array elements.
He asked me, pointer itself is a variable, so it will have its own address, and memory cells in the memory. Can we use a different cursor to point to the address of the other is not his pointer?
😀 Xin lỗi em chưa đọc kĩ mấy câu hỏi bên trên. Vậy cho em hỏi, khác nhau giữa con trỏ kiểu char với con trỏ của những kiểu kia là gì ạ. As e show can declare: char *s={“abc xyz”}
but not int * i ={“1,2,3”} . Thank you.
Char pointer pointers just another stop. But if you read pointers and arrays, it will have links, char pointer will be considered 1 array of characters should be treated as string.
have too.
He asked me which of the variable address pointer to the address of the cursor and different is not it ?
For example,
int a = 5;
int *p;
p=&the;
printf(“The tail chi Day : %p”,&the);
printf(“\ndia expenses of the variable that p pointing to% p”,p);
printf(“\ndia's sister p% p”,&p);
2 The first line are the same but the second line 3 then the other values sir ?? Expecting him to answer your question (((: .
Other than you, p address of a store, but it can save its address where.
Brother to brother asked them to read the books, they assume when we declare 1 Plate is a[2][3] then:
a is the address of a[0][0];
a + 1 is the address of a[1][0];
a + 2 is the address of a[2][0];
But when you use% p to check as it left his post to a + 1 points to the address of the section from immediately after a[2][3] always you sir. He explained households with children, I thank
Immediately after a[2][3] the elements?.
E test of a printed% p + 1
and% p &the[0][1] look.
#include “stdio.h”
#include “conio.h”
#include “math.h”
#include “string.h”
int main()
{
int x=5;
int * p =&x;
printf(“%dn”,*p);
p=(int*)calloc(5,sizeof(int));
for(int i=0;in<5;i )
*(p+i)=i+1;
for(int i=0;in<5;i )
printf("%4d",*(p+i));
getch();
}
he asked me what this code is wrong sir ???
What's wrong, you run up is knowing that.
include thì dùng kí tự not “” va dùng hàm calloc thì phải khai báo hàm stdlib.h. vì hàm này hỗ trợ nó.
Hello, Kids are having a confusing issue, I hope a little time for answers to help you.
#include
void func1(int a) {
int x;
x = a;
printf(“Address of x: %p, x = %dn”, &x, x);
}
void func2(int a) {
int y;
printf(“Address of y: %p, y =% d”, &and, and);
}
int main() {
func1(5);
func2(8);
return 0;
}
I run this program, then get results:
Address of x: 0x7ffeefc1a31c, x = 5
Address of y: 0x7ffeefc1a31c, y = 5
I want to ask is why the address and the value of the variable y address the variety and value of the variable x, although ạ?
I also tried but currently not understand why…
Address of x, y will return a that.
You can see the correction in it this point, I see no logical:
“The size of the pointer does not depend on the type of data, always have a fixed size 2 byte.”
According to miss, you're talking pointer void *. This variation depends on the microcontroller architecture, Microprocessor.
Pointer variable depending on the type of data it points to, the size of the cursor corresponding to the address of the memory cells.
God!
Thank you, I've corrected nhé. however the size of the cursor is always the same style though nhé.
Also, depending on the operating system each pointer variable, no matter what type of cursor (int, float, double,...) also accounts for the same number of bytes. Operating system 32 bit the pointer variable accounting 4 byte, operating system 64 bit the pointer variable accounting 8 byte.
he asked me, on his side declared 2 turning a , b, then in his jaw to make it 2 pointer * a, *b. I do not get that spot sir, he explained to me is not it, thank you
Use the cursor to save the value of the variable after that your jaw out. If you do not use the cursor in the function, it will not save the value of variable where.
Hello everyone, self-taught himself programming 1 months now. Lessons of the cursor on the page pretty vague cachhoc.net for learners, not express the essence between the cursor, IN MEMORY variables.
I have a document refer to page daynhauhoc.com, you can search google “C programming document for newbie” to find the document. It is easy to understand, bạn học sẽ nắm rõ được bản chất và cũng rất hài hước khi học nữa 😀
Cảm ơn bạn đã chia sẻ.