I am new to C, and I am having difficulty understanding the reason why the block of code below is not working.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *src = "http://localhost";
/* THIS WORKS
char scheme[10];
char *dp = scheme;
*/
//DOESN'T WORK
char *dp = malloc(10);
while (*src != ':') {
*dp = *src;
src++;
dp++;
}
*dp = '\0';
/* WORKS
puts(scheme)
*/
//DOESN'T WORK
puts(dp);
}
The expected output is http to stdout. In both cases dp should be a pointer to an array of char pointers (char **). However it is printing nothing when using malloc method. I ran the code through GDB and my src and dp are getting erased 1 character at a time. If I enclose the while loop into a function call it works. I figured that the reason was because parameters are evaluated as a copy. However, then I read that arrays are the exception and passed as pointers. Now I am confused. I can work around this, but I am trying to understand why this way doesn’t work.
You are changing
dpinside the looplet’s say
dphas the value0x42000000let’s say the loop went 4 times, so
dphas the value0x42000004now you put a null character at the address pointed to by
dpand then you try to print that null 🙂
Save
dpand print the saved valueIt works with
schemebecauseschemeis an array and you cannot change that address!