c - Collatz and Printing with Spaces -
i have following code:
#include <stdlib.h> #include <stdio.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> int main(int argc, char** argv) { const char* name = "collatz"; const int size = 4096; int num = atoi(argv[1]); int shm_fd; void *ptr; shm_fd = shm_open(name, o_creat | o_rdwr, 0666); ftruncate(shm_fd, size); ptr = mmap(0, size, prot_read, map_shared, shm_fd, 0); pid_t id = fork(); if (id == 0) { shm_fd = shm_open(name, o_rdwr, 0666); ptr = mmap(0, size, prot_write, map_shared, shm_fd, 0); while (num != 1) { sprintf(ptr, "%d", num); ptr++; if (num % 2 == 0) num /= 2; else num = 3 * num + 1; } sprintf(ptr, "%d", num); ptr++; } else { wait(null); printf("parent: %s\n", (char*) ptr); shm_unlink(name); } return 0; }
i print spaces between correct numbers haven't been able figure out when adding "%d "
or " %d"
, other formatting "things." when run program if type in 8 expect output be: 8 4 2 1
instead 8421
. being said, when input number 19 long number "correct" not formatted correctly. love formatting assistance please!
also seems algorithm might incorrect - if use 3 should expect result: 3, 10, 5, 16, 8, 4, 2, 1
, 31518421
you can use:
sprintf(ptr, "%d ", num);
this add space after number printing. can read more printf
formatting @ printf doc
as per incorrect result, can see if take first character of each number in: 3, 10, 5, 16, 8, 4, 2, 1
, 31518421
. because shifting ptr
1 after printing in ptr++;
. hence if printed 2 characters, second 1 gets overwritten on next step. need is:
int shift = sprintf(ptr, "%d ", num); ptr = ptr + shift;
or, in more concise form:
ptr += sprintf(ptr, "%d ", num);
here shift writer number of characters written, prevent being overwritten next call sprintf.
Comments
Post a Comment