notes74

notes74 - CS251 Class Notes Obtain the sum of the elements...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
CS251 Class Notes: 1/31/2005 Obtain the sum of the elements of an array: int a[20]; //Read elements int s = 0; for(int i = 0; i < 20; i++) { s += a[i]; //*(int *)(char *)a + i * sizeof(int) // Uses multiplication: slower } Using pointers: int s = 0; int *p = &a[0]; int *pend = &a[20]; while(p < pend) { s += *p; p++; //*(int *)p = *(int *)p + sizeof(int) // Is faster: only uses addition } Array Operater Assume int a[20]; a[i] == *(a + 1) Lets do pointer arithmetic using pointers of char (no scaling) String operations
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Strings in C are sequences of characters that are terminated by the NULL (0) character. int strlen(char *s) { int len = 0; while(*s != 0) { len++; s++; } return len; } char *strcat(char *s1, char *s2); s1 and s2 are concatenated and the result is stored in s1. strcat() returns s1. You must make sure that s1 has enough space to store both s1 and s2. Also you must be careful with strcpy(), etc. These functions don't allocate memory The only function that allocates memory is strdup which duplicates the content of a string. const char *s = "hello"; char *scopy = strdup(s); scopy = strdup(s); The memory allocated to store a string of size strlen(s) is actually strlen(s) + 1.
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

Page1 / 10

notes74 - CS251 Class Notes Obtain the sum of the elements...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online