How to store values in an array to a variable on MPLAB?

时光怂恿深爱的人放手 提交于 2019-12-13 06:22:23

问题


The following code works fine on CodeBlocks compiler but on MPLAB C18 compiler I don't get the same results. I am using PIC18 microcontroller.

Code

    int d[6];
    int all;

    d[0] = 6;
    d[1] = 4;
    d[2] = 8;
    d[3] = 0;
    d[4] = 0;

    all =  10000*d[0] + 1000*d[1] + 100*d[2] + 10*d[3] +  d[4];
    printf("%d", all);

Output on CodeBlocks: 64800

Output on MPLAB: -816

What is exactly the problem? Shouldn't this code work fine? Thanks!


回答1:


Objects that have the type int aren't guaranteed to be able to store values beyond -32767 or 32767. Your Code::Blocks implementation happens to extend this range, but your MPLAB C18 implementation (which isn't really a valid C implementation, by the way) doesn't. What you're seeing in your MPLAB implementation is undefined behaviour due to signed integer overflow. Use an unsigned type, and/or a wider type, such as long or long long. Don't forget to modify your printf format specifier accordingly. %u for unsigned int, %ld for long, %lu for unsigned long, %lld for long long, etc...




回答2:


according to this link , Your MCU is 8-bits system. so the length of the integer of your system is 16 bits. when you simulate your code with CodeBlocks, you are running your code with a 32-bits system ( or 64-bits system ) and the size of integer is 32 bits. so you will not get the same results. because in your MPLAP system you are overflowing the integer size



来源:https://stackoverflow.com/questions/16403009/how-to-store-values-in-an-array-to-a-variable-on-mplab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!