DAY13 Understanding C Pointers, Strings, and Stack Memory: A Practical Guide

编程达人挑战赛·第4期 10w+人浏览 240人参与

Understanding C Pointers, Strings, and Stack Memory: A Practical Guide

Pointers are one of the most powerful concepts in C programming. They allow you to directly manipulate memory, work with arrays and strings efficiently, and implement advanced data structures. In this tutorial, we’ll explore pointers as function parameters, string manipulation, and stack memory visualization.


1. Pointers as Function Parameters

1.1 Pass-by-Value

When a function receives arguments by value, it gets a copy of the variable. Modifying the parameter inside the function does not affect the original variable.

#include <stdio.h>

void swap(int a, int b) {
    int t = a;
    a = b;
    b = t;
}

int main() {
    int x = 3, y = 5;
    swap(x, y);
    printf("x = %d, y = %d\n", x, y); // Output: x=3, y=5
    return 0;
}

1.2 Pass-by-Reference (Pointer)

Passing a variable’s address allows the function to modify the original value.

void swap2(int *a, int *b) {
    int t = *a;
    *a = *b;
    *b = t;
}

int main() {
    int x = 3, y = 5;
    swap2(&x, &y);
    printf("x = %d, y = %d\n", x, y); // Output: x=5, y=3
    return 0;
}

Summary:

  • Pass-by-value: only reads the argument
  • Pass-by-reference: can read and modify the argument

2. Pointers and Arrays

  • The array name is a constant pointer to the first element.
  • int a[5]; int *p = a;
  • sizeof(a) returns the total array size; sizeof(p) returns pointer size.

Traversing an array using a pointer

#include <stdio.h>

void print_array(int *arr, int n) {
    for(int i = 0; i < n; i++) {
        printf("%d ", *(arr + i));
    }
    printf("\n");
}

int main() {
    int nums[5] = {1, 2, 3, 4, 5};
    print_array(nums, 5);
    return 0;
}

Stack Diagram for Array in Function Call:

Stack Frame for print_array:
+--------------------+
| arr (pointer)      | -> points to nums[0]
| n (int) = 5        |
+--------------------+

3. String Manipulation

C strings are null-terminated ('\0'), so a pointer is sufficient to traverse them.

Printing a string

void print_string(char *str) {
    while(*str) {
        putchar(*str++);
    }
    printf("\n");
}

3.1 Custom String Functions

mystrlen - Get string length
int mystrlen(char *str) {
    int len = 0;
    while(*str++) len++;
    return len;
}
mystrcpy - Copy string
void mystrcpy(char *dst, char *src) {
    while(*src) *dst++ = *src++;
    *dst = '\0';
}
mystrcat - Concatenate strings
void mystrcat(char *dst, char *src) {
    while(*dst) dst++;
    while(*src) *dst++ = *src++;
    *dst = '\0';
}
mystrcmp - Compare strings
int mystrcmp(char* s1, char* s2) {
    int i = 0;
    while(s1[i] && s2[i]) {
        if(s1[i] != s2[i]) return s1[i] - s2[i];
        i++;
    }
    return s1[i] - s2[i];
}

4. Convert String to Integer (myatoi)

int myatoi(char* str) {
    int num = 0, i = 0, sign = 1;
    if(str[0] == '-') { sign = -1; i++; }
    while(str[i]) {
        if(str[i] >= '0' && str[i] <= '9')
            num = num * 10 + (str[i] - '0');
        else break;
        i++;
    }
    return num * sign;
}

Stack Illustration:

Call: myatoi("-123")
+------------------+
| num = 0          |
| i = 0            |
| sign = 1         |
+------------------+

5. Count Character Types

Count uppercase, lowercase, digits, and spaces:

int Getcnt(char* str, int* upper, int* lower, int* digit, int* space) {
    *upper = *lower = *digit = *space = 0;
    int i = 0;
    while(str[i]) {
        if(str[i] >= 'A' && str[i] <= 'Z') (*upper)++;
        else if(str[i] >= 'a' && str[i] <= 'z') (*lower)++;
        else if(str[i] >= '0' && str[i] <= '9') (*digit)++;
        else if(str[i] == ' ') (*space)++;
        i++;
    }
    return 0;
}

6. Stack Memory Overview

When a function is called in C, its local variables and parameters are stored in a stack frame:

main() stack frame
+----------------+
| a = 3          |
| b = 5          |
+----------------+
swap2() stack frame
+----------------+
| a (pointer) -> &a in main
| b (pointer) -> &b in main
| t = 3          |
+----------------+
  • Pass-by-value: swap() copies values → original values in main unchanged
  • Pass-by-reference: swap2() receives pointers → modifies main’s variables

7. Conclusion

  • Pointers allow direct memory manipulation and efficient array/string handling
  • Custom string functions (mystrlen, mystrcpy, mystrcmp, myatoi) help understand underlying operations
  • Stack diagrams visualize how variables and pointers behave during function calls
  • Combining pointers with arrays and strings forms the foundation for more advanced C programming
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值