73_pdfsam_cs2022

73_pdfsam_cs2022 - Multidimensional arrays on the heap...

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

View Full Document Right Arrow Icon
Multidimensional arrays on the heap Creating a multi-D array on the heap is more involved Setup the array of row pointers and each row array explicitly // create array with 10 rows, 20 columns int **array2 = (int **) malloc(10 * sizeof(int *)); for(i=0; i<10; i++) array2[i] = (int *) malloc(20 * sizeof(int)); array2
Background image of page 1

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

View Full DocumentRight Arrow Icon
Arrays of strings Arrays of strings are just 2-D arrays of characters Because strings are just arrays of characters char *array2[] = {“Test.”, “Vacation!”, “”}; array2 (char **) T E S T . \0 V a c a t i o n ! \0 \0 (char *) (char *) (char *)
Background image of page 2
Example #include<stdio.h> #include<string.h> #include<stdlib.h> int main() { int str_count, j; char **str_array, buf[1024]; printf(“How many strings do you have? ”); fgets(buf, 1024, stdin); str_count = atoi(buf); str_array = (char **) malloc(str_count * sizeof(char *)); for(j=0; j<str_count; j++) { fgets(buf, 1024, stdin); str_array[j] = (char *) malloc(strlen(buf) + 1); strcpy(str_array[j], buf); } for(j=0; j<str_count; j++) printf(“%s”, str_array[j]); for(j=0; j<str_count; j++) free(str_array[j]); free(str_array); return 0; }
Background image of page 3

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

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 01/10/2010 for the course CS 2022 at Cornell.

Page1 / 6

73_pdfsam_cs2022 - Multidimensional arrays on the heap...

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

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