Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- /*
- INFO: This snippet is one of the "Extra Credit" assignments from Chapter 11 "Arrays and Strings" from LCTHW.
- The snippet uses the memcpy function to copy the bytes from a char array into an integer, since an integer takes up 4 bytes of space,
- and an array of char's takes N bytes, where N = its length.
- Here's a chart explaining how the result gets evaluated (the char's ASCII code is evaluated when I say '1st' * x, etc):
- N of Args
- 1 -> 1st
- 2 -> 1st + 2nd * (256)
- 3 -> 1st + 2nd * (256) + 3rd * (256^2)
- 4 -> 1st + 2nd * (256) + 3rd * (256^2) + 4th * (256^3)
- */
- //Change this to affect how large the array for the char's will be
- //Can't be larger than 4 else the integer storing the result is guaranteed to overflow (too large)
- #define CHAR_ARRAY_SIZE 4
- int main(int argc, char *argv[])
- {
- char array[CHAR_ARRAY_SIZE] = {'a', 'b', 'c', '\\'};
- int result[1] = { 0 };
- memcpy( result, array, CHAR_ARRAY_SIZE);
- printf("\n---- Overview of Operation ----\n");
- printf("Integer 'result' size: %ld bytes\nChar array size: %ld bytes\n",
- sizeof(result), sizeof(array));
- for(int i=0; i < CHAR_ARRAY_SIZE; i++) {
- printf("Arg #%d = '%c' (%d)\n",
- i+1, array[i], array[i]);
- }
- printf("Calculation of your result:\n");
- for(int i=0; i < CHAR_ARRAY_SIZE; i++) {
- if(i != 0 && i != CHAR_ARRAY_SIZE)
- printf(" + ");
- printf("%d * (256^%d)", array[i], i);
- }
- printf("\nResult = %d\n", result[0]);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement