vietwow
January 3rd, 2009, 06:17 AM
Dear all, I am newbie aobut C, I'm reading book http://beej.us/guide/bgc/output/html/singlepage/bgc.html and have some consfuse, need your help
First, when I need get a first element in a array, I need to declare a pointer for pointing to name of array without square brackets
For example :
int main()
{
char a[] = "Cats are better.";
char *p;
p = a;
printf("first element is : %c \n",*p);
And in the other way, I can declare a array with pointer :
int main()
{
char *array="hello world!";
char *parray, *first;
printf("first element : %c\n", *array);
printf("all : %s\n", array);
}
Both 2 codes are work well
From second code, I understand that code "char *array="hello world!";" will automatically create a array named array with content "hello world!" (so I could print all content with "array" variable in last line although I don't declare it before)
So now I use a new pointer for pointing to first element of variable "array" and print value of it but I got an "Segmentation fault". Detail is here :
#include<stdio.h>
int main()
{
char *array="hello world!";
char *parray, *first;
first=&array[0];
printf("first element : %c\n", *array);
printf("same : %s\n", *first);
}
run it :
[root@server ~]# ./taomang
first element : h
Segmentation fault
It can print *array but can't with *first
Anybody can explain me about this ?
Thanks
First, when I need get a first element in a array, I need to declare a pointer for pointing to name of array without square brackets
For example :
int main()
{
char a[] = "Cats are better.";
char *p;
p = a;
printf("first element is : %c \n",*p);
And in the other way, I can declare a array with pointer :
int main()
{
char *array="hello world!";
char *parray, *first;
printf("first element : %c\n", *array);
printf("all : %s\n", array);
}
Both 2 codes are work well
From second code, I understand that code "char *array="hello world!";" will automatically create a array named array with content "hello world!" (so I could print all content with "array" variable in last line although I don't declare it before)
So now I use a new pointer for pointing to first element of variable "array" and print value of it but I got an "Segmentation fault". Detail is here :
#include<stdio.h>
int main()
{
char *array="hello world!";
char *parray, *first;
first=&array[0];
printf("first element : %c\n", *array);
printf("same : %s\n", *first);
}
run it :
[root@server ~]# ./taomang
first element : h
Segmentation fault
It can print *array but can't with *first
Anybody can explain me about this ?
Thanks