Skip to main content

Con trỏ cấu trúc và ví dụ (Bài nháp)

Structure pointer and example

Khi làm việc với con trỏ, mình thỉnh thoảng cứ hay lẫn lộn giữa các ký hiệu & (Ampersand). *(Asterisk), -> (arrow), .(Full stop). Sau đây là một số ví dụ minh họa
Khi nào dùng dấu chấm, khi nào dùng dấu trỏ

Biến (Variable)

Về cơ bản, 1 biến được khai báo trong chương trình có 2 đặc điểm nhận dạng:
- Địa chỉ của biến đó ( biến đó được cấp phát 1 hoặc 1 vài ô nhớ trong RAM, nó giống như số nhà bạn vậy.
Khi ai đó cần chuyển thư, chỉ cần look up số nhà bạn, là có thể chuyển được)
- Giá trị của biến đó (ví dụ, nhà to nhà bé, nhà màu vàng, nhà màu đỏ ..vvv
Ví dụ:
Khi bạn khai báo
int foo = 10;
Thằng biến foo sẽ được chương trình cho 1 chỗ ở tại địa chỉ 0x1234 gì đó (phụ thuộc vào hệt điều hành, nền tảng phần cứng mà bạn đang sử dụng 8 bít, 16 bít, 32, 64.._
Giá trị thằng foo này là 10.
Trong ngôn ngữ C, khi bạn gọi
&foo sẽ trả về giá trị = 0x1234, là địa chỉ của thằng foo
foo sẽ trả về 10
*foo, ko trả về gì, thằng dấu asterisk này chỉ dùng cho con trỏ.
Question: tôi muốn đổi địa chỉ của thằng biến foo trong RAM thì làm thế nào?
Answer: Tác giả đoán là ko làm được :-(

Con trỏ (Pointer)

Con trỏ trước hết là 1 biến, vậy nó cũng có địa chỉ và giá trị của chính nó.
C cung cấp con trỏ như một cách dùng để truy nhập gián tiếp vào 1 biến khác. (Bình thường bạn có thể dùng tên biến, con trỏ cho phép bạn gán giá trị cho biến đó qua địa chỉ của biến đó)
Ví dụ:
int *p;                        //p được khởi tạo tại địa chỉ 0xABFF, nhưng chưa có giá trị
int  foo = 10;             // foo được khởi tạo tại địa chỉ 0X1234, với giá trị là 10
p = &foo;                 //p được gán giá trị, lúc này p = 0x1234, hay p đang trỏ vào địa chỉ 0x1234

Vậy
*p = 10                   //dấu *, thể hiện giá trị ô nhớ mà p trỏ đến, trong trường hợp này là ô nhớ tại địa chỉ 0x1234
p = 0x1234            //giá trị của p, hay tại ô nhớ 0xABFF, ô này có giá trị là 0x1234
&p = 0xABFF;      //địa chỉ của bản thân thằng p
*p = 12 ;              
//sau phép gán này, ô nhớ mà p đang trỏ đến (0x1234, giá trị 10) sẽ có giá trị là 12, hay foo =12. Vậy, gián tiếp qua p ta có thể gán giá trị cho foo

Cấu trúc (Structure)

typedef sfoo
{
      int id;
      char *name;
      sfoo *pnext;
}_sfoo_t;

Con trỏ cấu trúc (Structure pointer)

_sfoo_t *pssfoo;

Truy suất vào các phần tử của cấu trúc
Truy suất vào các phần tử của cấu trúc qua con trỏ cấu trúc


Danh sách liên kết (Link list)

(Cont)

Con trỏ hàm (Fucntion pointer)

(Cont)

Con trỏ hai chiều (2d pointer)

(Cont)


Reference

http://www-ee.eng.hawaii.edu/~tep/EE160/Book/chap12/subsection2.1.1.4.html
http://www.programiz.com/c-programming/c-structures-pointers
http://coltech.vnu.edu.vn/httt/components/com_joomlaboard/uploaded/files/thcs2_tuan8.pdf




Comments

Post a Comment

Popular posts from this blog

[STM32] How to configure Timer 1, Channel 3 is PWM 1kHz, duty cycle 20% to control BLDC motor

 To configure Timer1 for a 1 kHz PWM signal with a 20% duty cycle on an STM32H7S3L8 microcontroller, follow these steps: 1. Understand the Timer Parameters PWM Frequency : 1 kHz → Period = 1 ms. Duty Cycle : 20% → ON time = 0.2 ms. The timer’s clock frequency is derived from the APB clock (e.g., TIMCLK). Let’s assume you know the APB clock frequency. The Timer prescaler and auto-reload register (ARR) define the PWM frequency. 2. Compute Timer Parameters Formula: PWM Frequency = Timer Clock (Prescaler + 1) * (ARR + 1) \text{PWM Frequency} = \frac{\text{Timer Clock}}{\text{(Prescaler + 1) * (ARR + 1)}} PWM Frequency = (Prescaler + 1) * (ARR + 1) Timer Clock ​ For 1 kHz PWM: A R R = Timer Clock PWM Frequency ∗ ( Prescaler + 1) − 1 ARR = \frac{\text{Timer Clock}}{\text{PWM Frequency} * (\text{Prescaler + 1)}} - 1 A RR = PWM Frequency ∗ ( Prescaler + 1) Timer Clock ​ −...

How to use ChatGPT to get your resume shortlisted?

How to use ChatGPT to get your resume shortlisted? Core steps: Chat GPT -> Resume Creator -> LinkedIn(Copy the job description to ChatGPT) -> Add your personal information -> Copy output from ChatGPT to Instaresume.io to make the template -> Goto SkillSyncer to check ATS(Applicant Tracking Software) score, point out the missing keywords. Detail ☑️In my pursuit of job #opportunities, I encountered a familiar challenge - my resume seemingly disappeared into oblivion, yielding no responses despite my diverse skill set and numerous applications. ☑️As I delved into my research, I uncovered the existence of ATS software, the automated gatekeeper of #resumes, which swiftly filtered out those lacking relevant keywords. ☑️The outcome? Not just one #company, but over a dozen organizations recognized the potential in my resume, resulting in multiple shortlists and promising #job prospects! 💻If you want to supercharge your resume and unlock countless opportunities, don't miss o...

[Mentorship] First day at work - question for your co-workers (casual and friendly tone)

Summary Learn essential tips to make a positive first impression on your first day at a new job, ensuring success and connection with colleagues. Highlights⏰ Be punctual: Arrive early to show commitment. ( 15 minutes before your shift ) 🚫 Avoid gossip: Maintain professionalism and integrity. ❌ Don’t ask for time off: Show dedication to your new role. 🤝 Firm handshake: A confident greeting sets a great tone. 📚 Ask questions: Engage with your new role actively. 🗂️ Organize your workspace: Keep your area tidy for respect. ☕ Accept social invites: Build rapport with co-workers. Key Insights ⏳ First Impressions Matter: Your colleagues will form opinions quickly, so be on your best behavior right from the start. 🌟 Professional Appearance: Dressing smartly conveys seriousness about your role and can positively influence how others perceive you. 💬 Communication is Key: A warm greeting and engaging dialogue can help break the ice and make you more approachable. 📝 Active Learning: Asking ...