Tuesday, January 29, 2008

CSE2031 Lecture 7

void* ß malloc (int n)

int *p;

p = malloc (50 * sizeof(int));

Or

p = (int*) malloc(50*sizeof(int));

if((p=malloc(..) ) == null)

{

…exit(1)

}

free(p); //deallocate this space;

  • calloc enters 0's in memory for allocated space
  • go to man 3 malloc
    • talks about malloc calloc and realloc
    • realloc
      • allows you to resize memory partition previously allocated
  • arrays in C don't know how long they are

int x //declares an int

int f(int a , double b) // function that returns an int

int *f(int a, double b) //pointer to a unction that returns an int

int (*f)(int a, double b )//declares a function that takes parameters and returns an int


 


 


 


 


 


 


 


 


 

#include <stdlib.h>

#include <stdio.h>

#include <string.h>


 

int strCompare(const void *, const void *);

int intCompare(const void* p1, const void* p2);

int main(void)

{

char* A[] = {"30","3","20","2","0","5","10","1","40","4", "5"};

    for (i = 0;i<11;i++)

{

printf("%s ", A[i[);

}

putchar('\n');

qsort(A, sizeof(A)/sizeof(char *), sizeof(char *), strCompare);

return 0;

}

int strCompare(const void*p1,const void*p2)

{

int n = strcmp(*(char**)p1, *(char**)p2); //

if (n<0) return -1;

if (n>0) return 1;

return 0;

}

int intCompare(const void*p1, const void*p2)

{

int n1 = atoi(*(char**)p1);

int n2 = atoi(*(char**)p2); // atoi casts string to integer

if (n1<n2) return -1;

if (n1>n2) return 1;

}


 

(A, ... , cmp)

//int cmp(const void *p1, const void *p2)

//{int n1 =

int n2 =

if(n1<n2) return -1;

if(n1>n2) return 1;

return 0;


 


 

c struct

  • struct point {int x, int y};
    • point is the structure tag

No comments: