i'm making visual display pointers using table. first input length
works mychars
not being read. know there's new line after scanf
don't know how behaves. how mychars
's scanf
parsed in particular case?
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int length; printf("length? "); scanf("%d", &length); char *mychars = (char *)calloc(length, sizeof(char)); printf("mychars? "); scanf("%[^\n]s", mychars); printf("mychars \"%s\"\n", mychars); printf("pointer @ %p\n", mychars); if (strlen(mychars) == length) { printf("address location value\n"); int i; (i = 0; < length; i++) { printf("%-10p *(mychars+%02d) %3c\n", (mychars+i), i, *(mychars+i)); } } else { print("not right length"); } free(mychars); return 0; }
do not use scanf()
. evil. not handle problems , easy learners mis-use. use fgets()
.
// untested code int main(void) { size_t length; // use size_t array sizes printf("length? "); fflush(stdout); // insure prompt displayed before input. char buf[50]; if (fgets(buf, sizeof buf, stdin) == null) return -1; if (sscanf(buf, "%zu", &length) != 1) return -1; char *mychars = malloc(length + 2); // +1 \n, +1 \0 if (mychars == null) return -1; printf("mychars? "); fflush(stdout); if (fgets(mychars, length + 2, stdin) == null) return -1; // lop off potential \n mychars[strcspn(mychars, "\n")] = 0; printf("mychars \"%s\"\n", mychars); printf("pointer @ %p\n", (void*) mychars); // use `void *` %p if (strlen(mychars) == length) { printf("address location value\n"); size_t i; (i = 0; < length; i++) { printf("%-10p *(mychars+%02zu) %3c\n", (void*) (mychars + i), i, *(mychars + i)); } } else { printf("not right length\n"); // add \n } free(mychars); return 0; }
Comments
Post a Comment