zoukankan      html  css  js  c++  java
  • 面试宝典之预处理、const与sizeof

    #include <stdio.h>
    #define SUB(x, y) x - y
    #define ACCESS_BEFORE(element, offset, value) *SUB(&element, offset) =value
    
    int main(void)
    {
    	int i; int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
    	ACCESS_BEFORE(array[5], 4, 6);
    	for (i = 0; i < 10; ++i){
    		printf("%d ", array[i]);
    	}
    
    	return 0;
    }


    编译结果:




    分析:

    SUB(x, y) x - y

    ACCESS_BEFORE(element, offset, value) *SUB(&element, offset) =value

    ACCESS_BEFORE(array[5], 4, 6);->*SUB(&array[5], 4) =6 ->*&array[5] - 4 =6

    *&array[5]的值为6,则减去4等于2,将6赋值给2,则肯定是错误的。

    --------------------------------------------------------------------------------------------------------------------------------------------------------------------

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    struct {
    	short a1;
    	short a2;
    	short a3;
    }A;
    
    struct {
    	long a1;
    	short a2;
    }B;
    
    int main(void)
    {
    	char *ss1 = "0123456789";
    //	int ss[100] = "0123456789";
    
    	cout << sizeof(A) << endl;
    	cout << sizeof(B) << endl;
    	cout << sizeof(ss1) << endl;
    //	cout << sizeof(ss) << endl;
    
    	return 0;
    }



    假设去掉代码中的凝视,则编译结果为:



    由此可见 int ss[100] = "0123456789"; 这个语句是不对的,所以对其求sizeof也是不对的。

    -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


    #include <stdio.h>
    
    char var[10];
    int test(char var[])
    {
    	return sizeof(var);
    }
    
    int main(void)
    {
    	printf("%d
    ", test(var));
    	return 0;
    }


    var退化为数组的指针,而非数组。



  • 相关阅读:
    ThinkPHP5如何修改默认跳转成功和失败页面
    layer:web弹出层解决方案
    js插件---video.js如何使用
    【Leetcode】Search a 2D Matrix
    tableView 短剪线离开15像素问题
    经Apache将tomcat转用80port这两个域名
    [Python 2.7] Hello World CGI HTTP Server
    《代码的第一行——Android》封面诞生
    MySQL汇总数据
    Windows移动开发(一)——登堂入室
  • 原文地址:https://www.cnblogs.com/lytwajue/p/6812920.html
Copyright © 2011-2022 走看看