embedded c ppts

Upload: kapil-garg

Post on 06-Apr-2018

227 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Embedded c Ppts

    1/48

    1/17/2012 www.thinnkware.com 1

    A venture of KC Robotics & Embedded Pvt. Ltd.

    A Quick Introduction to Embedded C Programming

  • 8/3/2019 Embedded c Ppts

    2/48

    1/17/2012 www.thinnkware.com 2

    A venture of KC Robotics & Embedded Pvt. Ltd.

    C VS EMBEDDED C1. C is for desktop computers, but embedded C usually is for

    microcontroller based applications.

    2. C use the resources of desktop computers (memory, OS, etc), but

    Embedded C use only limited resources available in chip (limited RAM,

    ROM, ports, etc). Embedded C could be a subset of C.3. Usually in C what we develop would have headers like stdio.h, using

    which the system yields a output file feasible to that particular

    OS(windows, Linux etc), but when it comes to embedded C, everything

    is same except, you will get an output file which could be directly loaded

    in to the microcontroller.

    4. In C the output is an executable file, but in embedded C the output is a

    hexadecimal file.

    5. Libraries and headers used in C are different from that of Embedded C

    because the libraries used in embedded C differ in case of different

    microcontrollers.

  • 8/3/2019 Embedded c Ppts

    3/48

    1/17/2012 www.thinnkware.com 3

    A venture of KC Robotics & Embedded Pvt. Ltd.

    1. Write text of program (source code) using an editor.

    2. Run the compiler to check for errors and warnings in the edited

    3. Errors must be removed from the program to make it run successfully

    4. use the convenience of creating hex using the compiler from theexecutable file

    5. Burn the code on the microcontroller and check the output.

    WRITING YOURFIRST C PROGRAM:

  • 8/3/2019 Embedded c Ppts

    4/48

    1/17/2012 www.thinnkware.com 4

    A venture of KC Robotics & Embedded Pvt. Ltd.

    /* This is my first C program */

    #include // Header file to be included.

    int main() // Starting MAIN.{ // opening Brace.

    return 0;

    } // Closing Brace.

    EXAMPLE OF C PROGRAM

  • 8/3/2019 Embedded c Ppts

    5/48

    1/17/2012 www.thinnkware.com 5

    A venture of KC Robotics & Embedded Pvt. Ltd.

    UNDERSTANDING C SYNTAX

    All the syntaxes have been defined in C when it was developed.

    Syntaxes are to be followed very strictly while writing C program as

    they as the major source of error while compiling any C code.

    Each language has a syntax and semantics to work on and write

    programs in it. These syntax are checked by the compiler in the highest

    possible way so that at run time there should not b any issues in the

    program.

    A .c file is called a module. Many programs are composed of

    several .c files and libraries that are linked together during the

    compile process to create a single executable file.

  • 8/3/2019 Embedded c Ppts

    6/48

    1/17/2012 www.thinnkware.com 6

    A venture of KC Robotics & Embedded Pvt. Ltd.

    RESERVEDWORDS IN C

    1. C programs are constructed from a set of reserved words which provide

    control and from libraries which perform special functions. The basic

    instructions are built up using a reserved set of words, such as main, for,

    if, while, default, double, extern, for, and int, to name just a few.2. You cannot use default, for example, as the name of a variable. An

    attempt to do so will result in a compilation error.

    3. If you use a word which has already been adopted in a library, there will be

    a conflict between your choice and the library.

  • 8/3/2019 Embedded c Ppts

    7/48

    1/17/2012 www.thinnkware.com 7

    A venture of KC Robotics & Embedded Pvt. Ltd.

    STRUCTURE OF C PROGRAM

    The form of an ideal embedded C program should be:

    1. Preprocessor commands.

    2. Functions.

    3. Declarations4. Variables

    5. Statements

  • 8/3/2019 Embedded c Ppts

    8/48

    1/17/2012 www.thinnkware.com 8

    A venture of KC Robotics & Embedded Pvt. Ltd.

    VARIABLES IN C

    1. While making codes we need to store some values which keeps on varying

    from the beginning to the end of the execution of code. Depending on

    these values various decisions can be taken to change the execution flow.

    These varying quantities are known as variables.

    2. The name of these variables are actually what we call as declaration.

    The names given to these variables must not be a reserved word of C libraries.

    3. It will cause an error if you keep the same name for a variable and reservedword.

  • 8/3/2019 Embedded c Ppts

    9/48

    1/17/2012 www.thinnkware.com 9

    A venture of KC Robotics & Embedded Pvt. Ltd.

    DECLARATION AND DEFINITIONThese two words have different meaning in embedded C. Usually people use

    them interchangeably.

    Declaration: It is just writing the name of a variable to be used in the program.

    No memory has been assigned to the variable till declaration.

    For e.g.: int x.Definition: Giving a value to this variable that has been declared earlier is

    known as definition. After definition the memory space is allocated to the

    variable.

    For e.g.: x = 10.

    Declaration and definition: They both can be done together in a single line.

    For e.g.: int x = 10.

    Here also memory space will be allocated to the variable.

  • 8/3/2019 Embedded c Ppts

    10/48

    1/17/2012 www.thinnkware.com 10

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    THE COMPILATION PROCESS

  • 8/3/2019 Embedded c Ppts

    11/48

    1/17/2012 www.thinnkware.com 11

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    CONCEPT OF HEADERFILESUsually header files used in C are stdio and conio, but here in embedded C

    while working on microcontrollers the header files are not defined. They vary as

    per the use of microcontroller. For e.g.: the header file used while programming

    for AT89S52 is reg52.h.

    Header files have important functions in them which are used throughout theprogram to used pins and ports the microcontrollers and many other things.

    During compilation while checking for errors and warnings, the content of the

    header files are copied and are pasted into the main C program.

    We can not see it but it actually works in this way. This is how the functions

    written inside the header files are now included into the main C program. That is

    the reason why we always write as #include

  • 8/3/2019 Embedded c Ppts

    12/48

    1/17/2012 www.thinnkware.com 12

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    SCOPE : LOCALLocal

    These variables only exist inside the specific function that creates them. They

    are unknown to other functions and to the main program. As such, they are

    normally implemented using a stack. Local variables cease to exist once the

    function that created them is completed. They are recreated each time a functionis executed or called. They are declared and defined in the function only.

    For e.g.:

    int main()

    {

    int x,

    x = 10;

    x++;

    }

    Here x is a local variable which is local to main function. Any function outside

    main cannot access this x variable.

  • 8/3/2019 Embedded c Ppts

    13/48

    1/17/2012 www.thinnkware.com 13

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    SCOPE : GLOBALGlobalThese variables can be accessed (i.e. known) by any function comprising the

    program. They are implemented by associating memory locations with variable

    names. They do not get recreated if the function is recalled. They are declared

    and defined out of every function. They are also like preprocessor variables.

    They are defined outside of main and other functions.int y = 10;

    int main()

    {

    int x = 11;

    x++;

    y++;

    }

    Here y is a global variable and x is a local variable. Y has been declared and

    defined outside any function and hence can be used any where in the program as

    shown here in main.

  • 8/3/2019 Embedded c Ppts

    14/48

    1/17/2012 www.thinnkware.com 14

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    SCOPE OF OPERATORS AND VARIABLESC is a block structured language. Blocks are delimited by { and }. Every variable

    defined has a limit or area in which the variable is valid in the code. Blocks can be

    defined wherever a C statement could be used.

    int main

    {

    int a = 5;printf("\n%d", a);

    {

    int a = 2;

    printf("\n%d", a);

    }

    return 0;

    }

    Here a = 5 is valid throughout the program, but a = 2 is valid only in the inner

    opening and closing brace. Hence the first printf will print 5 and second prntf will

    print 2 as the variable in closest proximity of local brace will be given priority.

  • 8/3/2019 Embedded c Ppts

    15/48

    1/17/2012 www.thinnkware.com 15

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    VARIABLE STORAGE CLASSThe variable a = 5, can be used between anywhere in between its delimiting braces.

    Hence several scopes and types of variables are used as per the application needed.

    These are known as VARIABLE STORAGE CLASS. Other storage classes are:

    1) Auto : The default class. Automatic variables are local to their block. Their

    storage space is reclaimed on exit from the block.2) Register : These are variables which have the scope of an auto variable but are

    stored in a different memory to have faster access for use and change of

    variable. Use of the register class is not recommended, as the compiler should

    be able to make better judgment about which variables to hold in registers.

    3) static : On exit from block, static variables are not reclaimed. Their specialty

    is that they retain their value even after the braces have been executed. Fore.g.: static y = 5.

    4) extern: : These are the variables which are declared in a different file and are

    used in another C files. External variables are defined outside of any function.

    For e.g.: extern x = 5.

  • 8/3/2019 Embedded c Ppts

    16/48

    1/17/2012 www.thinnkware.com 16

    A venture of KC Robotics & Embedded Pvt. Ltd.

    DATA TYPES IN CThe most basic concept that is used in C programming is Data Types. The

    variables are the most used and important part of a C code, as they hold data

    based upon which decisions can be taken. But a limitation comes in size of the

    variable as some dont have memory size large enough to hold a big value or

    vice versa. This size of the variable for any variable is actually told by the

    Data type of the variable. Data type is written with the declaration. There aredifferent data types in C. Different data types, their size and value range that

    can be stored in them is mentioned here.

    Name Description Size Range

    char character 1 byte unsigned: 0 -255

    int integer *2 bytes unsigned:0-65535

    float Floatingpoint 4bytes +/- 3.4e +/- 38 (~7

    digits)

    double Double precision

    floatingpoint

    8bytes +/- 1.7e+/- 308

    (~15digits)

  • 8/3/2019 Embedded c Ppts

    17/48

    1/17/2012 www.thinnkware.com 17

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    THE BASICS OF THE C PR

    OGR

    AM Constants and Variables

    Operators: +, -, *, /, %, &, !, ^, |, ? :

    Expressions

    Statements

    floata = 1.5, b = a+3.1 ;

    or

    float b = a+3.1,a = 1.5 ;

    inta, b,c,d ;a = b = c = 10 ;

    or

    inta = b = c = d = 10 ;

    main( )

    {

    inti ;

    printf( "Entervalueofi " ) ;

    scanf( "%d", &i) ;

    if( i == 5)

    printf( "Youentered5" ) ;else

    printf( "Youenteredsomethingotherthan

    5" ) ;

    }

  • 8/3/2019 Embedded c Ppts

    18/48

    1/17/2012 www.thinnkware.com 18

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    RELATIONAL AND LOGICAL OPERATORS

    The following relational operators produce a true or false value.

    Operator Meaning

    > greater than

    >= greater than OR equal to

    < less than

  • 8/3/2019 Embedded c Ppts

    19/48

    1/17/2012 www.thinnkware.com 19

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    INCREMENT AND DECREMENT OPERATORS

    These are of two types: Increment and decrement.

    i++ post increment operator.

    i-- post decrement operator.

    ++i pre increment.

    --i pre decrement.

    In post method, the value of variable is incremented or decremented after the

    execution of this statement.

    In pre method, the value of variable is incremented or decremented before theexecution of this statement.

  • 8/3/2019 Embedded c Ppts

    20/48

    1/17/2012 www.thinnkware.com 20

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    ORDERAND PRECEDENCE OF OPERATORS

    Operator precedence describes the order in which C reads expressions.

    Lets evaluate this expression:

    a=4+b*2;

    Operators higher in the chart have a higher precedence, meaning that the C

    compiler evaluates them first. Operators on the same line in the chart have the same

    precedence, and the "Associativity" column on the right gives their evaluation

    order.

  • 8/3/2019 Embedded c Ppts

    21/48

    1/17/2012 www.thinnkware.com 21

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    OR

    DER

    AND PR

    ECEDENCE OF OPER

    ATOR

    SOperator type Operator Associativity

    Primary expression

    operator

    ) [] . -> expr++ expr-- left-to-right

    Unary operator * & + - ! ~ ++expr--expr(typecast) sizeof

    right-to-left

    Binary operator */ % + - >> = == != & ^ | && ||

    left-to-right

    Ternary Operator ?: right-to-left

    AssignmentOperators = += -= *= /= %= >>=

  • 8/3/2019 Embedded c Ppts

    22/48

    1/17/2012 www.thinnkware.com 22

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    LOOPS AND CONDITIONAL STATEMENTS

    Loops are most important part of C coding when making logic using different

    values of variables. Depending on the values of variables the flow of execution

    can be changed using these loops.

    Loops are also known as conditional statements as they work on certain values ofthe variables as selected by the user. Different types of loops have been

    implemented in C. They are: if, if-else, if-else ladder, while, do-while, for.

    Different loops have different syntax to implement in C code.

    The loops work on TRUE and FALSE conditions i.e. if the condition for the

    variable is true, the loop will execute and if the condition is false the loop will

    break.

  • 8/3/2019 Embedded c Ppts

    23/48

    1/17/2012 www.thinnkware.com 23

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    if-else CONDITIONAL STATEMENTThe IF statement checks for conditional execution of c-codes i.e. if the condition for theif block proves to be true, then statements within the if block get executed otherwise

    statements within else block get executed.

    /* if evaluated expression is not 0 */

    if (expression)

    {

    /* then execute this block*/

    }else {

    /* otherwise execute this block*/

    }

    The syntax is as follows:

    intmain( )

    {

    intnum ;printf( "Enteranumberlessthan10 " ) ;

    scanf( "%d", &num) ;

    if( num

  • 8/3/2019 Embedded c Ppts

    24/48

    1/17/2012 www.thinnkware.com 24

    A venture of KC Robotics & Embedded Pvt. Ltd.

    ITERATING LOOP CONTROL STATEMENTS

    while ( condition) /* while expression is true do*/

    {

    statement;/ * statement*/

    }

    do

    {

    statement; /* statement */

    }

    while ( condition); /* while expression is true*/

    for (initialization; condition; increment/decrement)

    {

    Statement; /* till condition doesnt go false*/

    }

  • 8/3/2019 Embedded c Ppts

    25/48

    1/17/2012 www.thinnkware.com 25

    A venture of KC Robotics & Embedded Pvt. Ltd.

    WHILE EXAMPLE

    intmain( ){

    inti = 1, j = 1 ;

    while ( i++

  • 8/3/2019 Embedded c Ppts

    26/48

    1/17/2012 www.thinnkware.com 26

    A venture of KC Robotics & Embedded Pvt. Ltd.

    SWITCH STATEMENTS:

    Switch statements can be used in place of conditional if statement.

    BREAK AND CONTINUE STATEMENTS:

    break statement helps the program to control branch out of the switch

    statement.continue statements can only be used in loop statements to skip executing

    statements after the continue statements for the iteration for which such

    conditions are implied in a c-program.

    GOTO STATEMENTS:goto makes the c-program unstructured. goto can help the program control to

    branch from one program section to anywhere within the program.

  • 8/3/2019 Embedded c Ppts

    27/48

    1/17/2012 www.thinnkware.com 27

    A venture of KC Robotics & Embedded Pvt. Ltd.

    SWITCH CASE EXAMPLE

    intmain( )

    {

    inti = ; scanf( "%d", &i);

    switch (i)

    {

    case 1 :

    printf( "I amincase1\n" ) ;

    break;

    case 2 :

    printf( "I amincase2\n" ) ;

    case 3 :

    printf( "I amincase3\n" ) ;default :

    printf( "I amindefault\n" ) ;

    }

    return0;

    }

    GOTO STATEMENT EXAMPLE

    intmain( ){

    intgoals ;

    printf( "Enterthenumberofgoalsscored);

    scanf( "%d", &goals) ;

    if( goals

  • 8/3/2019 Embedded c Ppts

    28/48

    1/17/2012 www.thinnkware.com 28

    A venture of KC Robotics & Embedded Pvt. Ltd.

    BREAK EXAMPLE

    intmain( )

    {

    inti = 1, j = 1 ;

    while ( i++

  • 8/3/2019 Embedded c Ppts

    29/48

    1/17/2012 www.thinnkware.com 29

    A venture of KC Robotics & Embedded Pvt. Ltd.

    FUNCTION: C-CODING BUILDING BLOCKS

    A function is a self-contained block of statements that perform a coherenttask of some kind. A Function is a series of instructions to run. A function

    may Return a value or may not return a value.

    A calling function may pass arguments to the called function or may not pass

    arguments to the called function.

    C program is a collection of one or more functions.A function gets called when the function name is followed by a semicolon.

    A function is defined when function name is followed by a pair of braces in

    which one or more statements may be present.

    Any function can be called from any other function. Even main( ) can be called

    from other functions.

    A function can be called any number of times.The order in which the functions are defined in a program and the order in

    which they get called need not necessarily be same.

    A function can be called from other function, but a function cannot be defined in

    another function.

  • 8/3/2019 Embedded c Ppts

    30/48

    1/17/2012 www.thinnkware.com 30

    A venture of KC Robotics & Embedded Pvt. Ltd.

    FUNCTION: CALLING, AR

    GUMENTSNow as the code has been divided into functions, they need to be synchronized.

    This is done by function calling. Whenever the code needs to execute a section,

    that specific function will be called.

    A calling function may pass arguments to the called function or may not pass

    arguments to the called function. Arguments are like input variables which canused to compute the execution of the function.

    But there is also a overhead while making function calls. The execution of the

    program jumps form the place of function call to the place of function definition.

    That waste the time of the microcontroller. A lot of function jumping is also

    hazardous to the execution time of the code.

    The solution to this type of waste is the use of Macros in the program. Butmacros should be used in place of small function usually single line function

    only because with macros the code size increases. Macros are discussed later.

  • 8/3/2019 Embedded c Ppts

    31/48

    1/17/2012 www.thinnkware.com 31

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    FUNCTIONS

    The ANSI C style of declaring and defining a function is:

    Return_type Function_name (parameters list)

    {

    statements.. /*Function definition*/

    }

    A function definition is where the function name, parameters, code and return

    type are specified. A function declaration is where the name and return type of a

    function are given. The definition of a function includes a declaration of that

    same function implicitly.

    A function can be declared many times (as long as the declarations declare thefunction to be of the same type) but can only be defined once. Declarations of

    functions are sometimes necessary to appease the compiler, which always

    assumes, if the information is not available, that all functions return int.

  • 8/3/2019 Embedded c Ppts

    32/48

    1/17/2012 www.thinnkware.com 32

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    FUNCTIONSThe ANSI C standard introduces function prototypes. An example is given

    below. It also allows function definitions to be written in the same form as the

    new prototypes. For e.g:

    double minimum(double, double); /* prototype of minimum() */

    int main()

    {printf("%f\n", minimum(1.23, 4.56)); /*Function called*/

    return 0;

    }

    double minimum(double x, double y) /* definition of minimum() */

    {

    if (x < y)

    return x;

    else

    return y;

    }

  • 8/3/2019 Embedded c Ppts

    33/48

    1/17/2012 www.thinnkware.com 33

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    Macros can be a useful way to customize our interface to C and make our code

    easier to read and less redundant.

    Macros are used to define constants.

    Macros can be used to improve code readability.

    They work at the time of preprocessing in compilation stages.

    Prior to compilation of the code, it replaces the name of the macros with the

    values defined for the respective names.

    For e.g:

    #define PI 3.14159

    They are globally declared. So, when compiler works it searches the word PI inthe whole code and replaces that word with 3.14159.

    Macros are faster in processing.

    Complex equations can also be defined as macros.

    MACROS

  • 8/3/2019 Embedded c Ppts

    34/48

    1/17/2012 www.thinnkware.com 34

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    MACROS

    Examples of macros: #define SQ(x) ( (x) * (x) )#define MIN(x,y) ( ((x) < (y)) ? (x) : (y) )

    In effect you can write often used simple functions as a macro rather than a

    function, the advantage is speed (there is no function call overhead) and no type

    definition is necessary (it can be reused for ints, doubles, floats etc.).

    The disadvantages are that if you use the macro several times, then the code willappear in your program several times, and there can be side effects caused by not

    creating new copies of the parameters (which is what happens when a function is

    called). When defining a macro there cannot be any spaces between the macro

    name and the parameter list; when calling a macro no such restriction holds.

    A general mistake which is made while defining functions in macros is not using

    brackets. For e.g: #define square(a+b) a+b * a+bThis will be interpreted as

    a+(b*a)+b

    So make sure to put brackets at correct places as

    #define square(a+b) (a+b) * (a+b)

  • 8/3/2019 Embedded c Ppts

    35/48

    1/17/2012 www.thinnkware.com 35

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    POINTERS IN CPointers are special kind of variables used in c to store addresses of another

    variable.

    Pointers are made to access the variables by their addresses rather than their

    name.

    Pointers are actually data-types which points to another variable of same data

    type.The *and & Operators :

    & : gives the address of something in memory, that is it generates a pointer

    to the object.

    * : gives what is pointed at by a pointer (called dereferencing).

    For e.g:

    int i = 0 , *j;

    j = &i;

    Here pointer j is pointing to the variable i. That means j holds the address of i.

    j = memory address of variable i.

    *j = integer value of variable i.

  • 8/3/2019 Embedded c Ppts

    36/48

    1/17/2012 www.thinnkware.com 36

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    POINTER

    S AR

    ITHMETICPointer arithmetic is same as that of a variable.For e.g:

    *j = *i + *j; *a = *a/* b; (a =*a+ b This gives an error).

    char* p, s[100];

    int * a, b[100];double * f, g[100];

    p = s; /* p points to s[0] */

    a = b; /* a points to b[0] */

    f = g; /* f points to g[0] */

    p++; /* p points to s[1] */

    a++; /* a points to b[1] */

    f++; /* f points to g[1] */

    The size of a pointer is always 4 bytes irrespective of the data type it is pointing

    to. This is because pointer holds the address of the variable not the value of it.

  • 8/3/2019 Embedded c Ppts

    37/48

    1/17/2012 www.thinnkware.com 37

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    Typecasting

    This is a method which is used to change the data type of a variable to another

    data type.

    For e.g:

    int i = 0; char c = c;

    i = (int) c;

    Here the data type of the character is changed into integer. The character c is

    stored into integer i. Thus its actually the ASCII value of c that is stored into

    integer i.

    An integer can also be stored in a character. But size of an integer is 2 bytes and

    size of a character is 1 byte. Hence while storing an integer into a character, data

    gets lost because character cant store an integer of 2 bytes.Similarly pointer datatype can also be changed like this.

    For e.g:

    int* i, char* j;

    j = (int*) i;

  • 8/3/2019 Embedded c Ppts

    38/48

    1/17/2012 www.thinnkware.com 38

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    NULL* AND VOID *VOID *: This is also a type of pointer which has no data type. Void means emptyhence the data type of this pointer is not defined. This means that this pointer is

    not pointing to any variable of any data type.

    To use such a pointer we have to type cast it into the variables data type to whom

    we want it to point to. We cant operate arithmetic or logical operation on this kind

    of pointer.

    NULL *: The constant 0 when used in a pointer context (e.g. assigned to a

    variable of any pointer type or compared with a pointer value) is replaced by a null

    pointer of the appropriate type. Such a pointer is used to indicate that a pointer

    does not point anywhere or is invalid.

    The preprocessor constant NULL can be used instead of the constant 0. Libraryfunctions that return pointers return NULL if an error occurs. The value of a

    pointer should always be checked to ensure that it is not NULL before attempting

    to dereference it. Attempting to dereference a NULL pointer will give a run-time

    error on some systems.

  • 8/3/2019 Embedded c Ppts

    39/48

    1/17/2012 www.thinnkware.com 39

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    DER

    IVED DATA TYPES: ArraysArrays are an example of derived data types.

    Arrays holds several variables of same data type. Mentioning the size of the

    array is important. The array terminates with a null \0 at the end.

    Size of an array = no. of variables + 1(for null).

    The variables in an array are indexed. The first variable is given the index 0and it increments as the no of variables increases.

    For e.g.

    int arr[4] : means it is an array which holds 4 variables of integer data type +

    null character.

    Null character is not visible to the user. Even there is no need to put a null

    character when defining an array. The compiler automatically puts it before

    closing brace of the array.

  • 8/3/2019 Embedded c Ppts

    40/48

    1/17/2012 www.thinnkware.com 40

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    DERIVED DATA TYPES: Arrays

    int arr[] = {1,2,3,4,5,6}: in such a case of declaration and definition together

    we dont need to declare the size of the array.

    In later case first variable i.e. 1 is at index 0, 2 is at index 1 and increments for

    the rest of the array. Here arr is the name of the array and also arr holds

    the base address of the array i.e. the address of the first variable of the array.The array holds contiguous address spaces in memory starting from index 0 to

    the end.

  • 8/3/2019 Embedded c Ppts

    41/48

    1/17/2012 www.thinnkware.com 41

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    DERIVED DATA TYPES: StringsString is also a derived data type.

    String is an array of characters terminated by a null character.

    It is actually a pointer which points to a character which is written in the

    enclosed quotes.

    For e.g : char* str = Thinnkware

    Here str is a character pointer which is pointing to first character i.e T enclosedin quotes.

    If we do str++, then str will start pointing to h i.e. second character of the word

    enclosed in quotes.

    Lets take an example:

    char* abc = Thinnkware welcomes you;

    Here *abc = T,

    If abc++ is written then,

    *abc = h.

    And it keeps on incrementing so on with the address. The strings also ends with

    a terminating null character.

  • 8/3/2019 Embedded c Ppts

    42/48

    1/17/2012 www.thinnkware.com 42

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    DYNAMIC MEMORY ALLOCATIONSTill now what we talking about in the difference between declaration and

    definition is about the memory space occupied. That memory space is actually

    static memory.

    This memory is used when we define variables or any other data while writing the

    program. After compilation the memory space is allocated to the required

    members from the static memory. These are the cases where we know the amountof size to be allocated to a variable or array or any member.

    Here is a pictorial representation of static memory.

    The variables are saved in them as soon as they are

    defined and also are fetched from the same segments

    when needed in the program.

  • 8/3/2019 Embedded c Ppts

    43/48

    1/17/2012 www.thinnkware.com 43

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    DYNAMIC MEMORY ALLOCATIONS

    This is a method which is used to allocate memory to any variable or derived data

    type at run-time i.e. the time when the code is executing.

    There are 3 methods or functions to allocate memory dynamically:

    1) Malloc()

    2) Calloc()

    3) Realloc()

    Malloc() and calloc() are used to allocate new memory whereas realloc is used to

    allocate the free memory which has been allocated earlier.

    Mostly malloc() and calloc() are used. These functions work on pointer theory.

  • 8/3/2019 Embedded c Ppts

    44/48

    1/17/2012 www.thinnkware.com 44

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    Malloc: The memory allocated using this method may be contiguous may not be

    contiguous. The memory allocated has garbage values.

    For e.g: id we have to allocate a memory of 6 integers,

    int* memory;

    memory = (int *) malloc (6 * sizeof (int) );

    Here to store 20 integers, typecasting is used before malloc because mallocreturns void*. So we have to typecast it to the pointer data type that we have to

    store.

    In case of malloc the memory assigned to malloc in non contiguous form the

    memory pointer points to the first address of the memory space. This memory

    space then points to the next memory address allocated to the malloc.In this way it keeps a track of the individual elements of the array. A pictorial

    representation gives you a clear idea.

    MALLOC

  • 8/3/2019 Embedded c Ppts

    45/48

    1/17/2012 www.thinnkware.com 45

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    MALLOC

  • 8/3/2019 Embedded c Ppts

    46/48

    1/17/2012 www.thinnkware.com 46

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    Calloc: The memory allocated using this method is always contiguous. The

    memory allocated is initialized with value 0. Thats why calloc() is faster as

    compared to malloc().

    For e.g: If we have to store 6 integers,

    int * memory;

    memory = (int*) calloc (6, sizeof ( int) );

    CALLOC

  • 8/3/2019 Embedded c Ppts

    47/48

    1/17/2012 www.thinnkware.com 47

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    Free: It is the method to free the memory allocated using malloc() or calloc(),

    so that the memory can be used further for allocation.

    For e.g:

    Free (memory);

    It will free the memory allocated during previous malloc() or calloc()

    operations.

    FREE

  • 8/3/2019 Embedded c Ppts

    48/48

    1/17/2012 www.thinnkware.com 48

    A venture of KC Robotics & Embedded Pvt.

    Ltd.

    The most important part after successful coding is its documentation.

    Documentation is needed for code readability. Documentation or comment lines

    begin with a double slash ( // ) and all text to the end of the line is considered a

    comment. Documentation should appear :

    before the main program (program header)

    before each function (function header) before or next to lines of code within a function (line comments)

    For e.g.: int add(int x, int y); // Function to add 2 numbers

    The next important part of C coding is the name conventions used. Names

    should be meaningful in the application domain, not the implementation

    domain. Note that well-structured code is layered internally, so your

    implementation domain is also the application domain for lower levels.

    For e.g.: int AdditionOfNumbers(int FirstNumber, int SecondNumber);

    Embedded C Coding Guidelines