/* Ferworn F06. A review of pointers, strings and arrays. Like it or not */ #include <stdio.h> #include <string.h> void printastring(); char *returnastring(); void changeastring(char *); void changeanarray(int [],int); void dealwitha2darray(int [][],int,int); int main() { char a='a', b='b', c='c'; char *ptr; char astring0[] = "This is a string!"; char *astring1 = "This is another string!"; char *astring2 = astring1; int onedarray0[5] = {5,4,3,2,1}; int *onedarray1; int twodarray0[3][3]={{0,1,2},{3,4,5},{6,7,8}}; int i,j,k; ptr = &a; printf("a == %c \n",a); printf("ptr == %c \n",*ptr); ptr = astring2; printf("ptr == %c \n",ptr); printf("astring0 == %s ",astring0); printf("it has a length of %d characters\n",strlen(astring0)); printf("astring1 == %s ",astring1); printf("it has a length of %d characters\n",strlen(astring1)); /* fun with 1d arrays */ onedarray1 = onedarray0; printf("onedarray0 == %d %d %d %d %d\n", onedarray0[0], onedarray0[1], onedarray0[2], onedarray0[3], onedarray0[4]); printf("onedarray1 == %d %d %d %d %d\n", *(onedarray1), *(onedarray1 + 1), onedarray1[2], onedarray1[3], onedarray1[4]); /* we put the fun in functions */ printastring(); printf("%s\n", returnastring()); changeastring(astring0); printf("The changed string: %s\n",astring0); changeanarray(onedarray0,5); printf("onedarray0 == %d %d %d %d %d\n", onedarray0[0], onedarray0[1], onedarray0[2], onedarray0[3], onedarray0[4]); dealwitha2darray(twodarray0,3,3); } void printastring() { printf("This is a string printing function.\n"); } char *returnastring() { return "This is a string being created and returned"; } void changeastring(char *astring) { char temp[50] = "<start>"; strcat(astring,"<end>"); strcat(temp,astring); strcpy(astring,temp); } void changeanarray(int array[],int length) { int i; for(i=0;i<length;i++) array[i] = 9; } void dealwitha2darray(int array[][3],int a, int b) { int i,j; for(i=0;i<a;i++) for(j=0;j<b;j++) printf("%d ",array[i][j]); printf("\n"); } /* Output a == a ptr == a ptr == � astring0 == This is a string! it has a length of 17 characters astring1 == This is another string! it has a length of 23 characters onedarray0 == 5 4 3 2 1 onedarray1 == 5 4 3 2 1 This is a string printing function. This is a string being created and returned The changed string: <start>This is a string!<end> onedarray0 == 9 9 9 9 9 0 1 2 3 4 5 6 7 8 */