I am new to C and reviewing some source code. But I am not sure what is happening with this code snippet.
I really don’t think it is doing anything, as in the debugging the output seems to be the same for tempstr.
This is what I think, correct if I am wrong.
*(tempstr + strlen(line)) is adding the length of line to tempstr and dereferencing and assigning the 0x0 converted to a char?
char line[128], tempstr[128]
strcpy(line, "AUTO_ANSWER_CALL = 1");
strcpy(tempstr,line);
*(tempstr + strlen(line)) = (char) 0x0; // Confusing part
This is a pointer value:
This is another pointer value (which points to
5elements beyond thetempstrpointer value):This is an integer:
Therefore, this is a pointer value (which points to
strlen(line)elements beyond thetempstrpointer value):And this is dereferencing that pointer:
It’s ensuring that the character at index 20 of tempstr, immediately beyond the “AUTO_ANSWER_CALL = 1” characters, is null: i.e. it’s ensuring that the string is null-terminated.
That string already is null-terminated, by the way (so that last statement is redundent): because strcpy copies the string including the implicit null-termination character.
These aren’t the same thing:
strlen(line)equals 20, butsizeof(tempstr)equals 128.That’s exactly the same things as:
Just a different way of writing it.
If tempstr is NOT a null terminated string then
strlen(tempstr)is undefined (‘undefined’ means that it’s meaningless and dangerous, a bug, and shouldn’t be used): thestrlenfunction isn’t valid except when it’s used on a string that’s already null-terminated.