0

So I was given this sample code as an exercise and am having trouble understanding how exactly it works. I ran it and using some print statements I know it takes a string from the standard input and makes smaller versions of the string so hello becomes ello, then llo, then lo, then o. What I'm confused about is how source and target can have 1 added to them since their data type is a character pointer. How exactly does this code work?

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {

    char* target = malloc(100*sizeof(char));
    char* source = argv[1];
    char tmp;
    while ((*source) != 0) {
        tmp = *source;
        *target = tmp;
        target = target + 1;
        source = source + 1;
    }

    return 0;
}
acqwctm
  • 27
  • 5
  • 2
    "I know it takes a string from the standard input" it does not – user3159253 Apr 15 '16 at 17:20
  • 1
    Adding one to a pointer to a position in an array makes the pointer point at the next element of the array. That's what you're seeing — the pointer moves one step at a time through the string. The code you show is remarkably clumsy — and vulnerable to a long command-line argument overflowing the allocated buffer. – Jonathan Leffler Apr 15 '16 at 17:21
  • @JonathanLeffler: It also doesn't null-terminate the `target`-string, which is probably not a good habit to get into. – EOF Apr 15 '16 at 17:24
  • Sorry I mean it takes a string from the input parameters – acqwctm Apr 15 '16 at 17:25
  • 1
    @EOF: Yeah, that too — the string should be null terminated and you must be careful to ensure that copies of strings are null terminated. In the given code, it doesn't matter because the copy isn't used, but in anything intended to be useful, it certainly does. The whole code should arguably use `char *target = strdup(argv[i]);`, after checking that `argv[1] != NULL`. And it should do something with the copy (after checking again). But that doesn't help in understanding how pointers work — so the code has some (limited) pedagogic value even though it has no practical value as working code. – Jonathan Leffler Apr 15 '16 at 17:27

0 Answers0