Hi all,
Need explanation how can i print this :
if i useCode:int *pa = {1,2,3,4,5,6};
printf("%d",pa) ===> result is 1
and if i use
printf("%d",pa+1) ==> result is 5
Hi all,
Need explanation how can i print this :
if i useCode:int *pa = {1,2,3,4,5,6};
printf("%d",pa) ===> result is 1
and if i use
printf("%d",pa+1) ==> result is 5
printf("%p\n", (void*)mypointer);
still error ==> segmentation fault
ok, i show the code:
and error isCode:int main() { int *pa = {1,2,3,4,5,6} for(j=0; j<5;j++) { printf(" pa = %d \n",pa[j]); } }
Code:$ ./a.exe 3 [main] a 2996 _cygtls::handle_exceptions: Error while dumping state (pro bably corrupted stack) Segmentation fault (core dumped)
Good. That means that today we have learned that you cannot use array-initializer notation to initialize pointers. (The only exception is string literals; those are stored and have addresses. 1, 2, 3, 4, 5, 6 does not.) Didn't you wonder why your compiler said
Code:temp.c: In function `main': temp.c:4: warning: initialization makes pointer from integer without a cast temp.c:4: warning: excess elements in scalar initializer temp.c:4: warning: (near initialization for `pa') temp.c:4: warning: excess elements in scalar initializer temp.c:4: warning: (near initialization for `pa') temp.c:4: warning: excess elements in scalar initializer temp.c:4: warning: (near initialization for `pa') temp.c:4: warning: excess elements in scalar initializer temp.c:4: warning: (near initialization for `pa') temp.c:4: warning: excess elements in scalar initializer temp.c:4: warning: (near initialization for `pa')
Yes, there are a lot warning when compilation. I ask this because when i compare it with string that you have mentioned it.
Usually i can use
char *x = "hello";
printf("%s \n",x) ==> hello
printf("%c \n",x[4]) == o
Thanks you, so i understand those values have no address
Code:const char *x = "hello"; printf("address of x is %p\n", (void*)&x); printf("string pointed to by x is %s\n", x); printf("address of string pointed to by x is %p\n", (void*)x); printf("x[4] is %c\n", x[4]); printf("address of x[4] is %p = %p + sizeof(x) * 4\n", (void*)&x[4], (void*)x);
Last edited by robwhit; 10-27-2008 at 08:20 AM. Reason: i don't need no stinkin' code tags... or const qualifiers...
Use [code] tags robwhit you noob
When you assign string literals to char pointers, you should use const char pointers.
http://cpwiki.sourceforge.net/Common...kes_and_errors
And remember that in C, a lot of warnings are actually errors. Do not ignore them (a good idea is to actually make the compiler treat the warnings as errors, so it does not compile if there are any warnings). A good programmer fixes all warnings.
Perhaps you meant
Code:int pa[] = {1,2,3,4,5,6}; printf("pa = %d\n", *pa); printf("*(pa+1) = %d\n", *(pa+1));