Please include the question in the body of the article, not just in
the subject:
what different between 1 and 2, why?
Add:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
If your compiler didn't warn you about the implicit or missing
declaratins for malloc, memset, sprintf, and printf, crank up the
warning level until it does.
Slightly better:
int main(void)
{
char **buf;
int nodesize = 1024;
int nodenum = 10;
int i;
buf = (char **)malloc(nodenum);
Here you allocate just 10 bytes, but you treat buf as a pointer to the
first element of an array of 10 char* objects. Unless your system has
1-byte pointers, this isn't going to work.
Don't bother to cast the result of malloc; it's not necessary,
and it can mask certain errors (like forgetting the required
"#include <stdlib.h>").
I changed to the above line to:
buf = malloc(nodenum * sizeof *buf);
and the program worked.
for (i=0; i<nodenum; i++) {
buf = (char *)malloc(nodesize);
Again, drop the unnecessary cast.
memset(buf, 0, nodesize);
sprintf(buf, "%d", (i+1)*1000+10);
if (i == 0) {
printf("%p: %s\n", buf[0], buf[0]); /* 1 */
}
}
printf("%p: %s\n", buf[0], buf[0]); /* 2 */
return 0;
}
You're using "%p" to print char* values. "%p" expects a void*
argument. As it happens, the standard guarantees that void* and char*
have the same representation, so this should work. But it's a good
idea to get into the habit of casting pointer arguments to void* when
using "%p" (unless they're already of type void*). (Most casts are
unnecessary; arguments to printf, where the compiler doesn't have
enough information to perform the right implicit conversion, are an
exception.)