C语言中指针及内存的常见使用(每个例子含可运行demo)(1/3)

这篇博客详细介绍了C语言中的指针使用,包括指针内部构造和指针加减法。此外,还讨论了动态内存管理的calloc, malloc, realloc函数,特别是realloc的安全性和性能特点。最后,提到了C中char*的操作规范以及结构体指针的使用,强调了结构体指针可以视作结构体数组。" 106193730,4932205,Ubuntu18.04 编译 Pulseaudio 14.x 指南,"['Linux', 'Ubuntu', '音频处理', '编译构建', 'Pulseaudio']
摘要由CSDN通过智能技术生成

一、指针

1. 指针内部构造

2. 指针加减法(pointer arithmetic)

str中的地址相隔为1,因此对于我们的指针p+=1的时候,p会根据自己的数据类型,自动加到下一个地址元素

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define COUNT 4

int a[COUNT];
float b[COUNT];
double c[COUNT];
long long int d[COUNT];
short int e[COUNT];
long int f[COUNT];

// illustrate the different amounts that are added to an address by C's address arithmetic
int main()
{
    int* pa;
    float* pb;
    double* pc;
    long long int* pd;
    short int* pe; // we could just use 'short' here
    long int* pf;

    // first let's look at the sizes of our array types
    printf("sizes are: int %d; float %d; double %d; long long int %d; short int %d; long int %d\n", sizeof(int),
           sizeof(float), sizeof(double), sizeof(long long int), sizeof(short int), sizeof(long int));
    // NOTE: because of historical reasons a plain 'int' can vary in size between machine architectures. On some
    // microprocessors it is 2 bytes long while on Intel processors it is 4 bytes
    // if we want to be explicit (and more portable), then use 'long int' for a 32 bit integer instead of just 'int'

    // initialize our array and pointers
    pa = a;
    pb = b;
    pc = c;
    pd = d;
    pe = e;
    pf = f;
    for(int i = 0; i < COUNT; i++) {
        a[i] = i;
        b[i] = (float)i;
        c[i] = (double)i;
        d[i] = i;
        e[i] = i;
        f[i] = i;
    }

    // let's do some arithmetic
    pa += 1;
    pb += 1;
    pc += 1;
    pd += 1;
    pe += 1;
    pf += 1;
    // and print out the results ...
    // NOTE: the addresses have been increased by the correct amount 4 for 'int', 'float' and 'long int'
    // 8 for 'double' and 'long long int' and 2 for 'short int'
    printf("address of a is %p [%d]; value of pa is %p [%d]; value pointed to by pa is %d\n", a, a, pa, pa, *pa);
    printf("address of b is %p [%d]; value of pb is %p [%d]; value pointed to by pb is %f\n", b, b, pb, pb, *pb);
    printf("address of c is %p [%d]; value of pc is %p [%d]; value pointed to by pc is %f\n", c, c, pc, pc, *pc);
    printf("address of d is %p [%d]; value of pd is %p [%d]; value pointed to by pd is %lld\n", d, d, pd, pd, *pd);
    printf("address of e is %p [%d]; value of pe is %p [%d]; value pointed to by pe is %hd\n", e, e, pe, pe, *pe);
    printf("address of f is %p [%d]; value of pf is %p [%d]; value pointed to by pf is %ld\n", f, f, pf, pf, *pf);

    return 0;
}

二. calloc, malloc, realloc

1. malloc & realloc

realloc 就是在当前的基础上重新指定其大小

#include <stdio.h> 
#include <stdlib.h> 
int main() 
{ 
   int *ptr = (int *)malloc(sizeof(int)*2); 
   int i; 
   int *ptr_new; 
     
   *ptr = 10;  
   *(ptr + 1) = 20; 
     
   ptr_new = (int *)realloc(ptr, sizeof(int)*3); 
   *(ptr_new + 2) = 30; 
   for(i = 0; i < 3; i++) 
       printf("%d ", *(ptr_new + i)); 
  
   getchar(); 
   return 0; 
} 

2. realloc

我们在这里需要与malloc做的区别是:realloc会将分配的地址初始化,可以理解为 realloc =malloc + memset(0)

realloc更加安全, 但是性能表现略慢于malloc

Note: It would be better to use malloc over calloc, unless we want the zero-initialization because malloc is faster than calloc. So if we just want to copy some stuff or do something that doesn’t require filling of the blocks with zeros, then malloc would be a better choice.

二者的语法也有区别

// C program to demonstrate the use of calloc() 
// and malloc() 
#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
int *arr; 
	
// malloc() allocate the memory for 5 integers 
// containing garbage values 
arr = (int *)malloc(5 * sizeof(int)); // 5*4bytes = 20 bytes 
	
// Deallocates memory previously allocated by malloc() function 
free( arr ); 
	
// calloc() allocate the memory for 5 integers and 
// set 0 to all of them 
arr = (int *)calloc(5, sizeof(int)); 
	
// Deallocates memory previously allocated by calloc() function 
free(arr); 

return(0); 
} 

三、 c中对于char* 操作

1. C中不能直接赋值,而是要采用strcpy或者strncpy

#include <stdio.h>
#include <string.h>

int main () {
   char src[40];
   char dest[12];
  
   memset(dest, '\0', sizeof(dest));
   strcpy(src, "This is tutorialspoint.com");
   strncpy(dest, src, 10);

   printf("Final copied string : %s\n", dest);
   
   return(0);
}

四、结构体指针

可以理解为结构体指针,也可以理解为结构体数组,关键是看malloc的大小

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define COUNT 4

typedef struct {
    int a;           // 4 bytes
    double b;        // 8 bytes
    int c;           // 4 bytes
    double d; // 8 bytes
} MYSTRUCT;

// illustrate the different amounts that are added to an address by C's address arithmetic
int main()
{
    MYSTRUCT *test1;
    test1 = (MYSTRUCT *)calloc(1, sizeof(MYSTRUCT));
    test1->a = 1;
    test1->b = 1;
    printf("a = [%d], b = [%lf]\n", test1->a, test1->b);

    MYSTRUCT *test2;
    test2 = (MYSTRUCT*)calloc(COUNT, sizeof(MYSTRUCT));
    for(int i = 0; i < COUNT; i ++) {
        test2[i].b = 1;
    }
    printf("========================================\n");
    MYSTRUCT *p, *q;
    void* v;

    printf("size of MYSTRUCT = %d\n", sizeof(MYSTRUCT));
    // p = (MYSTRUCT*)calloc(COUNT, 24); // DO NOT DO THIS!
    p = (MYSTRUCT*)calloc(COUNT, sizeof(MYSTRUCT));
    for(int i = 0; i < COUNT; i++) {
        p[i].a = i;
        p[i].b = i*30;
        p[i].c = i * 20;
        p[i].d = 10*i;
    }
    for(int i = 0; i < COUNT; i ++) {
        printf("a = [%d], b = [%lf], c = [%d], d= [%lf]\n", p[i].a, p[i].b, p[i].c, p[i].d);
        printf("a = [%p], b = [%p], c = [%p], d= [%p]\n", &p[i].a, &p[i].b, &p[i].c, &p[i].d);
        printf("addr = [%p], addr_b = [%p]\n", &p[i], &p[i].b);
        printf("=========\n");
    }
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值