// file: lecture_14/example.cc // // a simple program to play around with data types, including // pointers and arrays // // system include files // #include "example.h" // function: main // // main program starts here // int main(int argc, char** argv) { // declare a character string // /* char joe[] = "Joe"; // declare some other arrays // float sig[] = {1.0, 2.0, 3.0}; short int ssig[] = {27, 99, 39}; short int* ptr = ssig; fprintf(stdout, "sig = %u\n", ssig); fprintf(stdout, "the value at memory location (%u) = %d\n", ssig, *ptr); float* fptr = (float*)(void*)ssig; fprintf(stdout, "the value at memory location (%u) = %f\n", ssig, *fptr); // open a file // FILE* fp = fopen(argv[1], "r"); if (fp == (FILE*)NULL) { fprintf(stderr, "[%s] Ouch - an error has occurred\n", argv[0]); return -1; } // allocate space to hold each line // char buf[MAX_LINE_LENGTH]; // count the number of lines // long num_lines = 0; while (fgets(buf, MAX_LINE_LENGTH, fp)) { num_lines++; } fprintf(stdout, "the number of lines in %s is %d\n", argv[1], num_lines); // we must rewind the file // rewind(fp); // size the lines array to only what I need // char* lines[num_lines]; // loop over the file // num_lines = 0; while (fgets(buf, MAX_LINE_LENGTH, fp)) { // copy the line to lines[] // lines[num_lines] = new char[strlen(buf) + 1]; // lines[num_lines] = (char*)malloc(strlen(buf) + 1); strcpy(lines[num_lines], buf); num_lines++; } fprintf(stdout, "number of lines read = %d\n", num_lines); for (long i = 0; i < num_lines; i++) { fprintf(stdout, "[%d] %s", i, lines[i]); } // clean up memory // for (long i = 0; i < num_lines; i++) { delete [] lines[i]; } // close file // fclose(fp); */ // allocate more memory // char* pchr = new char[MAX_LINE_LENGTH]; strcpy(pchr, "Today is a Friday after an exam."); fprintf(stdout, "pchar: %s\n", pchr); fprintf(stdout, "pchar+1: %s\n", pchr + 1); float* fptr = (float*)pchr; fprintf(stdout, "float value = %f\n", *fptr); /* char* str = pchr; long i = 0; while (*str != (char)NULL) { fprintf(stdout, "[%d] value = %c (%d)\n", i, *str, *str); i++; str++; } long N = 3; short int ssig[N] = {27, 99, 39}; short int* ptr = ssig; i = 0; while (N > 0) { fprintf(stdout, "[%d] value = %d\n", i, *ptr); N--; i++; } */ // exit gracefully // return(0); }