hello, I am trying to understand how pointer works, but there is something I dont get:
insert
Code:
#include <stdio.h>
main()
{
int *pointer;
int number=10;
pointer=&number;
printf("\nvalue of number: %d",number);
printf("\nvalue of what the pointer points to: %d",*pointer);
printf("\nmemory location of number: %x",&number);
printf("\nmemory location of pointer: %x",pointer);
}
in this example I assing to pointer the memory location of number (pointer=&number), and everything works.
I was trying to do the same with a string of characters, but it doesnt work as I expected:
insert
Code:
#include <stdio.h>
main()
{
char *pointer;
char string[]="blabla";
pointer=&string[0];
printf("\ncontent of string: %s",string);
printf("\ncontent of what the pointer points to: %s",*pointer);
}
the second program core dumps printing the value of *pointer.
Dont understand why.
I arrived to this example because I was thinking about a way to prevent the use of the malloc system call.
I mean that I can define a string in this way:
char *string=malloc(10 * sizeof(char));
but i thought I could do the same defining a pointer to char, a char array and make the pointer points to the first character of the char array
PS: I have found that a small change in the second program produces the expected behaviour:
insert
Code:
#include <stdio.h>
main()
{
char *pointer;
char string[]="blabla";
pointer=&string[0];
printf("\ncontent of string: %s",string);
printf("\ncontent of what the pointer points to: %s",pointer);
}
I dont understand why this works... I was expecting that *pointer would point to the char array