Codes n' scripts, for you !

hits on our blog !
Feel free to follow us, feel free to reblog and
like this stuff, feel free to contact us.
Thanks !

FAVOURITES

following

Dynamic memory allocation in C V2

/*
 * @author: Jodvellu 2012
 * Version 2 with functions.
 * - - - - - - - - - - - - - - - - -
 * Output:
 * - - - - - - - - - - - - - - - - -
 * #0:0
 * #1:5
 * #2:10
 * #3:15
 * #4:20
 * - - - - - - - - - - - - - - - - -
 */

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

#define SIZE 5

void setvalues_ptrarray(int*);
void print_ptrarray(int*);

int main() {
    int *ptr = malloc(SIZE * sizeof(int));
    int n;
   
    if(ptr != NULL) {
        setvalues_ptrarray(ptr);
        print_ptrarray(ptr);
    }
    free(ptr); // Free *ptr.
    return 0;
}

void setvalues_ptrarray(int *ptr) {
    int n;
    for(n = 0; n < SIZE; n++)
        *(ptr + n) = n * SIZE;
}

void print_ptrarray(int *ptr) {
    int n;
    for(n = 0; n < SIZE; n++)
        printf(“#%d:%d\n”, n, *(ptr + n));
}


Posted: Tuesday May 1st, 2012 at 10:24pm