You are here:

C/Pointers

Advertisement


Question
1)  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()".  

Answer
Hello 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.

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.