C语言——杂实例

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

void f (int **p);

void change(int *tmp_t)
{

    *tmp_t =1;

    return;
}
/*
这个函数才是真正的交换
*/
void real_swap(int *real_a, int *real_b)
{
	int real_tmp;
	
	real_tmp = *real_a;
	*real_a = *real_b;
	*real_b = real_tmp;
}

void swap(int *a1,int *b1)
{
    int *tmp=NULL;
    tmp=a1;
    a1=b1;
    b1=tmp;
}

void memorylocate(char **ptr)
{
    *ptr=(char *)malloc(1*sizeof(char));
}

int main(void)
{
    int a=2;
    int b=3;
    
    const char *ptr = (char*)&a;
    /*常量指针指向的值不能改变,但是这并不是意味着指针本身不能改变,
    常量指针可以指向其他的地址。
    */
    ptr = (char*)&b;//is legal
    
    /*常量指针说的是不能通过这个指针改变变量的值,
    但是还是可以通过其他的引用来改变变量的值的。*/
    //*ptr = (char)5; //error: assignment of read-only location
    b = 5;
    a = 9;
    
    int *m = &a;
    int * const npt = &a;
    a = 9;
    *npt = 18;
    *m = 20;
    /*指针常量指向的地址不能改变,但是地址中保存的数值是可以改变的,可以通过其他指向改地址的指针来修改。
    */
    //npt = &b; error: assignment of read-only variable `npt'
    
    printf("Before swap a=%d  b=%d\n",a,b);
    swap(&a,&b);
    printf("After swap a=%d  b=%d\n",a,b);
    real_swap(&a,&b);
    printf("After swap a=%d  b=%d\n",a,b);
    
    char *buffer = (char*)&a;
    memorylocate(&buffer);
    strcpy(buffer,"12345");
    printf("buffer %s\n",buffer);
    
    int bita = 0;
    bita = bita | (0x1f << 3) | (0x07 << 23);   

    bita = 0;
    //bita |= ('0b'11111<<3);
    
    //int * p = (int * ) malloc (4 * sizeof(int));
    int * p = (int * ) malloc (8);
	char * cp = (char * ) malloc (4 * sizeof(char));
    if(NULL == p)
	{
		printf("malloc failed\n");
		return -1;
	}

	if(NULL == cp)
	{
		printf("malloc failed\n");
		return -1;
	}

	*(p+0) = 1;
	*(p+1) = 3;
	*(p+2) = 5;
	*(p+3) = 4;
	*(cp+0) = 1;
	*(cp+1) = 3;
	*(cp+2) = 5;
	*(cp+3) = 4;
	//*(p+4) = 6; //编译通过,但无法运行。
	printf("%d\n", *(p+3));

	free (p);

	free (cp);
	
    
    
//    int i=90;
//    *(int *)0x28ff00 = 0x130;
////    int n =0,*p = &n,**q = &p;
////    double *b = (double *)malloc(sizeof(int));
////    b=0;
////    b=NULL;
//    printf("0x%0x\n",&i);
//    printf("Hello world!\n");
//
//    int * a ;
//    a = NULL ;
//    f (&a);
//    printf("%d",*a);
//    free(a);
//
//    int in = 11;
//    int *p, *q;
//
//    p = &in;
//    q = &p;
//
//    *p = 40;
//    //(**q) = 60;
//    int tmp = 0;
//
//    change(&tmp);
//
//    printf("################ tmp = %d /n");
//    ;
//

    return 0;
}

/*
c语言实现函数给主函数中的指针赋值的方法

*/
void f (int **a)
{
    *a = (int *)malloc (sizeof (int )) ;
    **a = 1 ;
}
Before swap a=20  b=5
After swap a=20  b=5
After swap a=5  b=20
buffer 12345
4


Terminated with return code 0
Press any key to continue ...

 

 

posted @ 2018-08-19 15:04  wdliming  阅读(320)  评论(0编辑  收藏  举报