C/Pointers
Expert: Narendra - 6/23/2006
Question1) void RLeft(const char *input, char *output, int length)
{
int i;
for(i=0;i<length && *input != '\0';i++)
{
*output = *input;
printf("%c %s\n",*input,output);
input++;
output++;
}
}
2) The another catch is here which is against the advice of Yashvant Kanitkar:
main()
{
char *name[3];
int i;
printf("%u %u %u\n",name[1],name[2],name[0]);
for(i=0;i<=2;i++)
{
printf("Enter name[%d]",i); scanf("%s",name[i]);
}
}
My system is Linux version 2.6.12 (root@Knoppix) (gcc-Version 3.3.6 (Debian 1: 3.3.6-7)) #2 SMP Tue Aug 9 23:20:52 CEST 2005
The problem is that address of one of elements of array is 0; hence resulting in 'Segmentation Fault'. Obviously it is kernel protected area.
3) main()
{
struct book
{
char name;
float price;
int pages;
}
struct book b[3];
int i;
for(i=0;i<=2;i++)
{
printf("enter name price and pages\n");
scanf("%c %f %d",&b[i].name, &b[i].price, &b[i].pages);
}
for(i=0;i<=2;i++)
printf("%c %f %d\n",b[i].name, b[i].price, b[i].pages);
}
linkfloat()
{
float a=0,*b;
b=&a;
a=*b;
}
The above program gives the error that "two or more datatyoes in declaration of 'b'".
But this code is replica of program give in Yashvant Kanitkar, only difference being that size of structure array b has been reduced to 3.
Also I am unable to understand the need of "linkfloat()".
AnswerHello Ravi,
I have few suggestions for you:
1. Write clearly of what is happening and what you expect to happen.
2. Do indent your programs. It will improve readability and helps debugging and maintainability.
Here are my answers to your questions:
1. You haven't specified what is the problem!
2. If it hadn't crashed, I would have surprised!
You are declaring:
char *name[3];
And using it as:
scanf("%s",name[i]);
Remember that name[i] is still uninitialized. And since this is a pointer, you have to initialize it with a valid variable and then only you can use it.
So, allocate memory and use them. Then it will not crash.
3. Yes, there is a mistake and hence you are getting the compiler error! You have missed a semicolon!
struct book
{
char name;
float price;
int pages;
} <=====You have missed a semicolon here!
struct book b[3];
Observe that, you have missed placing a semicolon after defining book.
Add that and your code will compile without errors.