Iam3R 24 Junior Poster

I ran this short test on VC++ 2010 Express and Code::Blocks

int main()
{
    if ( -1 < ( unsigned char ) 1 )
        printf("true 1\n");
   if ( -1 < ( unsigned short ) 1 )
        printf("true 2\n");
   if ( -1 < ( unsigned int ) 1 )  
        printf("true 3\n");
   if ( -1 <  1 )
        printf("true 4\n");
}

and got the following results

I understood it clearly now.

unsigned char ch = 1;
if ( -1  <  ch )

the ch will be converted to int ,so -1 and 1 both are integers and hence the condition is true.

if ( -1  <  (unsigned char ) 1 )

same as above. and same for short int.

if ( -1  <  (unsigned int ) 1 )

now lhs (-1) is int and rhs (1) is unsigned , so -1 will be converted to unsigned int, giving the biggest value.
hence the condition is false.

please correct me if i am wrong.

Iam3R 24 Junior Poster

why would -1 be converted to unsigned int when (unsigned char) 1 can just be converted to int which has more width than unsigned char and is already the type of -1?

Did you mean to compare -1 and 1U?

i dont understand what does the if understand below statements as

if ( -1 < ( unsigned char ) 1 )
   if ( -1 < ( unsigned short ) 1 )
   if ( -1 < ( unsigned int ) 1 )  
   if ( -1 <  1 )

and when -1 gets converted to unsigned.

Iam3R 24 Junior Poster

hi,

how the below code is generating out put as " -1 < ( unsigned char ) 1 ".

i read in many books saying when we do operation with singed and unsigned value always the resultant will be data type that has more width .

i understand that -1 when compared with unsigned should be coverted to unsigened int and yeild a big value than 1.
but the out put is different.

whats the story..
please help.

main() {
  if ( -1 < (unsigned char) 1 )
      printf("-1 is less than (unsigned char) 1");
  else
      printf("-1 NOT less than (unsigned char) 1");
}
Iam3R 24 Junior Poster

Hi.Thanks a lot from abhimanipal.

instead of

Display_AdcX( adcvalmax[] )

use

Display_AdcX( adcvalmax )

this does not work

#
for(i,m=0;i,m<8;i++,m++){ //IS THIS FOR STATEMENT RIGHT? ****************

there are other error

your way of commenting is not correct.

Iam3R 24 Junior Poster

Oh. I didn't realize you are doing that.

Back to the original:

Let's say, e is a power of 2, so the code never enters the else clause. Can you tell what would be the result?

what ever is the value of 'e' it will definently become 1 at the last iteration.

now the problem is

if e is even initially the return value should be the value in if part, if not the return value should be base multiplied by the value in the if part

Iam3R 24 Junior Poster

How about

else if ( e % 2 == 1 ) {
                         p = b*p;
                         e -= 1;
                 }

p is getting overwritten here how will we add that here.

if ( e % 2 == 0) {
       p = b*b;
      e/=2; 
 }
Iam3R 24 Junior Poster

Hi,
i have written a program to find the power of two numbers using iteration.

The problem here is that to return the correct out put for even powers but not for odd powers.
b = base , e = expo ,p= power( b, e);;

for even powers the statements in the if ( e % 2 == 0) are enough.
for odd powers we need to perform one extra multiplication with base.

but i am unable to control the if and else properly.

if i control else it will become a probelm in if or vice versa.

please suggest me on this.

i want to perform the power with order ( log n ) and order (1).

int power( int b , int e)
 {       
         int  p = 0;
         if ( e < 0 )
                 return NEG_POWER;
         
         if ( e == 0)
                 return 1;
         if ( b == 0 )
                 return 0;
         while ( e )
         {       
                 if ( e % 2 == 0) {
                         p = b*b;
                         e/=2;
                 }
                 
                 else if ( e % 2 == 1 ) {
                         p = b*p;
                 }
         }       
 }

i am trying foll way:
but its a problem in if for odd powers.

int e2 = e ; // at the start
       else if ( e % 2 == 1 ) { 
                  if ( e2 % 2 == 0)
                               return p;
                        else {
                                p = b*p;
                                e /= 2;
                    }
}
Iam3R 24 Junior Poster

Hi,

#include<stdio.h>
int main( void )
{
        float a = 0.2;
         if( a > 0.2 )
                printf( "\n a is greater than 0.2" );
        else if( a < 0.2 )
                printf( "\n a is less than 0.2" );
        else
                printf( "\n a is equal to 0.2" );
         return 0;
}

the out put of the above program is "a is greater than 0.2" .

the reason i think is that, the variable a stores 0.2 as 0.259595, but why is it so.

if i want to compare two float values for some precession how to do that.


Regards,
Iam3R

Iam3R 24 Junior Poster

what is the correct declaration of pointer to a pointer to array of N elements.
( i want to store address of pointer to an array of n elements )
i am using the below declarions seperately , but getting errors.

int (*p)[4];
          int (*p1) (*)[4] = &p;
          int *p1 (*)[4] = &p;
          int (*p1) ( (*)[4] ) = &p;

any idea please..

Iam3R 24 Junior Poster

but that is not O(n).

it is O(n2)

Iam3R 24 Junior Poster

Why? Because the ISO standards committee said so. Didn't your momma ever tell you "because I said so" in response to your why question???

To use your overused word, why?

If you plan on writing your own compiler that breaks C syntax, then you obviously are capable of working out the level of technical difficulty yourself. And if you can't figure out the technical difficulty, you're not a competent enough coder to write a compiler...

you can call me what ever you want.

but i cannot give these answer to my students.

Iam3R 24 Junior Poster


1. Because they said so. Why would you want to comment out the comments? If you want to comment out a large block of code that may contain comments, then there are other ways to do it. I do it like this.

#if 0
// code here
#endif
int main( void )
{
           some statements;
   
                /* some comments
                                          /*  comments
                                                      end of comments */
                  end of some comments */
 some more statements
return 0;
}

in the above code the below line creates a problem as its not any valid C statement. end of some comments */ my question is---- why compiler implementers/preprocessor implementers have not handled such a simple situation .

push the /* in to stack and pop when matching end */ is found.


2. Not sure what you are asking. int array[200] = {1,2,3,4,5} In this array the first five elements are initialized to the values shown, all remaining array elements are initialized to 0. Is that your question?

yes the same.

when an array is initialized partially why it initializes remainig elements to zero.


3. why array bound check is not implemented in C.

i want to know the technical difficulties involved in implementing these.

Iam3R 24 Junior Poster

1. Why Nesting of comments is not supported by c.
code does not involve much complexity to have that.

2. Why Array partial initialization have zero appended.
why it cannot do in normal declaration.

3. continued....

Thanks,
3R

Iam3R 24 Junior Poster

Because C is fairly lax about types and if it has an automatic conversion from the type given to the type required then it will silently do it for you. C knows how to convert float to int so it just happens.

This was one of the issues fixed in C++ which is much more strongly typed, compile the code you have given as C++ and you get the following diagnostic messages

bytes.c:6: warning: passing `double' for converting 1 of `float get_float(int)'
bytes.c:9: warning: passing `double' for converting 1 of `float get_float(int)'

so i can say that when passing arguements in function, c compiler will do promotions and demotions to the data. but it will not genereate any error / warning for mismatching type in function declaration and function call.


it will only generate errors in below cases:

when return type in the declaration does not match with the return type is definition.

when the number of arguments deos not match in prototype and definition.

Iam3R 24 Junior Poster

What were you expecting...my crystal ball's on the fritz and the Amazing kreskin is busy right now..

compiler uses the function declaration to know
1. type of values it can take as argument,
2. number of arguments it is allowed to pass and ofcourse with respective type.
3.the return type of the function.

now this is what i am expecting :
when compiler saves the above info to make sure that call is valid, why cant it check when passing the different type values.

as declaration in line 1 says float get_float(int num); accepting / passing int value.

but the calls in line no 5 and line 8 are using float argument.

Iam3R 24 Junior Poster

Hi,
I have written a program just to check the behaviour of the compiler.

i expected an error in function call statement.

but its not generating any error.

the declaration of function we include to check the type of args and no of args and return value of function.

but its not working as i expected.

please provide comments on this.

float get_float(int num);
int main( void )
{
        float f;
        f = get_float(12.34);
        printf("%f", f);
        f = 12.34;
        f = get_float(f);
        printf("%f", f);

        return 0;
}

float get_float( int num)
{
        return 12.32;
}
Iam3R 24 Junior Poster

That's coz you're using %f for scanning a double. Use %lf.

Hi,
rather old post but correct one for disscussions.
i once used the %lf in one thread but it was said that there is no such specifier.


http://www.daniweb.com/forums/thread241546.html

can some one explain whcih is the corect fomat specifier for reading double values using scanf statement.

Iam3R 24 Junior Poster

Hi,

Please some one clarify what does the below snippets mean and the compiler assumptions.

which one is the correct one to use, what is the problem with others.

main() 
                     {
                        
                      }
void main() 
                     {
                        
                      }
int main() 
                     {
                        
                      }
int main() 
                 {
                        
                   return 0;
                  }
Iam3R 24 Junior Poster

> i have read that new line character gets converted to \r\n when writing characters to a file
> and converted to new line again when reading.
You heard wrong then.
On *nix systems, there is no translation at all.

Check again, your input file simply has two newlines at the end of it.

Try od -Ax -t x1z file.txt

i have done as you suggested.

i got the results as

spark@spark-desktop:~/Cprogs/Files$ od -Ax -t x1z noc.txt
000000 68 65 6c 6c 6f 0a 0a >hello..<
000007
but i dont understand what does that mean and result as well.
i am sure that i am using only one enter at the end of line.
when i dont press enter key and try to find out the no of characters its giving 6 for the input Hello
how is that possible ? is it taking on \n as default. ?
i am working on ubuntu 9.04

Iam3R 24 Junior Poster

Hi ,

i have read that new line character gets converted to \r\n when writing characters to a file
and converted to new line again when reading.

but i observed one thing here.

i have written contents hello followed by return key .

and i have written a program to count the no of characters i got the result as 7.
then i tried printing character and its ascii value then its printing two characters with the same ascii value( 10 ) at the end . that mean its not converting \r\n to \n . if so the out put should be 6.

this is the program:

#include<stdio.h>
int main(int argc,char *argv[]) {
        FILE *fp;
        char ch;
        int nc=0;
        fp=fopen(argv[1],"r");
        if(!fp)
                printf("file doesnot exist\n");
        else {
        while((ch=fgetc(fp))!=EOF)
        {
                printf(" < %c > and < %d > \n", ch , ch );
                nc++;
        }
        printf("no of chars=%d",nc);
        }
return 0;
}

i many of the forums many ppl mentioned that there is no difference between text and binary on *nix systems.

the out put i got is:

< h > and < 104 >
< e > and < 101 >
< l > and < 108 >
< l > and < 108 >
< o > and < 111 >
<
> and < 10 >
<
> and < 10 >
no of chars=7

i am running programs on …

Iam3R 24 Junior Poster

If dst and src share bytes within n, anything could technically happen, but let's assume a very simple common scenario. Say you want to do memmove(array + 1, array, 2) where array is defined as a string ("abc"). With memmove you'd expect the result to be "aab", but with memcpy that might not happen. Here's what could happen with the above algorithm:

a = "bc", b = "abc, *a++ = *b++ == "aac"
a = "c",  b = "ac", *a++ = *b++ == "aaa"
done

So the result is "aaa"...hmm, not quite right, is it? memmove fixes this problem by checking for overlap and adjusting the logic to do something safer, and at a glance it's easy to see that the function can be slightly slower:

These algorithms are naive, but memcpy is less restricted and thus more open to optimization. However, in my experience, memmove isn't likely to be a bottleneck, so removing the risk of undefined behavior by using memmove instead of memcpy is worth it.

Please have a look at this program.

if i use your definitions the out is same as you explained , but when i use standard functions the out put of memmove and memcpy are same.

if memmove and memcpy are implemented differently then we should get different out put using those functions.

but it is not the case with std functions.

you said overlap might cause problem in memcpy.

does the standard definition of memcpy varies from system to system …

Iam3R 24 Junior Poster

Hi ,

when i run the program i got the same out put by using memcpy and memmove
but i dont understand the difference between them.

manual page says that memory area should not overlap in memcpy but can in memmove.

what is meant by moving memory and how its safe . why memcpy is dangerous.

int main() {

        char strmc[]="strings are good";
        char strmm[]="strings are good";

        printf("before memcyp : the string <%s> \n", strmc);
        memcpy(strmc+1,strmc+0,4);
        printf("after memcpy the string <%s> \n",strmc);

        printf("before memmove : the string <%s> \n", strmm);
        memmove(strmm+1,strmm+0,4);
        printf("after memmove the string <%s> \n",strmm);

return 0;
}

the out put what i got is :

before memcyp : the string <strings are good>
after memcpy the string <sstrigs are good>
before memmove : the string <strings are good>
after memmove the string <sstrigs are good>

Iam3R 24 Junior Poster

here i have two bubble sort versions.

void bsort()
{
        int i,j,jc=0,ic=0,temp,swap=1;

       //for(i=0;i<NOE & swap;i++){ this one or
        for(i=0;i<NOE-1 & swap;i++){ \\ this 
        swap=0,ic++;
         for(j=0;j<NOE-1-i;j++){
                jc++;
                if(a[j]>a[j+1]){
                        temp = a[j];
                        a[j] = a[j+1];
                        a[j+1] = temp;
                        swap = 1;
                        }
                }
        }
printf("jc=%d ic=%d\n",jc,ic);
}

i checked it .

in first case it only repeats one extra time which is not nedded .
other than that is there any situation where we get different results with different stataments.
Thanks,

Iam3R 24 Junior Poster

Spot the undefined behavior in the above code. Happy learning! ;)

i dint see any undefined behaviour statements in the code.

can you please spot it.

Iam3R 24 Junior Poster

pls. help me in how to program that...

char str[]="the quick brown fox and the lazy dog" ;
int i =0;
while(str[i] !=' ' )
 i++;
strcpy(str,str+i+1);

works if the above is your requirement, analyze it yourself.
happy learning...........

Iam3R 24 Junior Poster

below is one simplest code to illustare the pyramid of number.

void piramid(int const c)
{
int r, x;

for (r = c; r > 0; r--)
{
for (x = 1; x < = (2 * c - r); x++)
{
if (x < r) printf(" ");
else if (x <= c) printf("%d", x - r + 1);
else printf("%d", (2 * c - r) - x + 1);
}
printf("\n");
}
}

is there any other method that uses just the loop counters to print the pyramid with out the help of any other variables.

i just want to replace the statements x - r + 1 and (2 * c - r) - x + 1 by just r or x.

Thanks ,

WaltP commented: Adter 80+ posts, don't you think it's time to learn how to FORMAT code? -2
Iam3R 24 Junior Poster

Hi,

i understand the ieee 754 representation. but can some one explain why we need to add specifically 127 to the power of 2.


for ex:

5.75 ;

101.110 can be written as 1.01110 * 2 ^ 2

127 +2 = 129 . i.e 10000001

now IEEE 754 of
5.75 is 0 1000 0001 01110 0000 0000 0000 0000 00

thanks,

Iam3R 24 Junior Poster

Hi ,

i know one method of deleting a record from a binary file.

that is :

read the contents of the file and every time check for some criteria based on which we want to delete the record.

if record does not match criteria then write to new file if it matches then dont write that record continue with the next record.

i have written a program for this and is working fine.

but othe method : tried opening a file in rb+ mode and read the file till i find the record when i find the record , going to next record and write that record in previous place and next next record in next prev place and so on as below but its not working. please help me.

void Delete_Player( char *name )
{
        FILE *infp , *outfp ;
        int nor, wchfile, found = 0 ;
        Player_t P, temp ;

        infp = fopen ("PLAYERsInfo.dat","rb+");
        //outfp = fopen("Dup.dat","wb");

         if ( !infp ) {
                printf (" ( \"%s\" ) open failed \n" , "PLAYERsinfo.dat");
                return ;
        }

        while (1 == ( nor = fread (&P , sizeof ( P ), 1 , infp) ) )
        {
                if ( ! strcmp ( name , P.name ) ) {
                        cnt_rec++;
                        break ;
                }
       //nor++;( got it invalid) ( corrected )
       cnt_rec++;//fwrite ( &P , sizeof (P), 1 , outfp );
        }

        if ( feof ( infp ) )
        {
                printf("No ( \" %s \") is present \n", name );
                return ; …
Iam3R 24 Junior Poster

Hi ,

i know one method of deleting a record from a binary file.

that is :

read the contents of the file and every time check for some criteria based on which we want to delete the record.

if record does not match criteria then write to new file if it matches then dont write that record continue with the next record.

i have written a program for this and is working fine.

but othe method : tried opening a file in rb+ mode and read the file till i find the record when i find the record , going to next record and write that record in previous place and next next record in next prev place and so on as below but its not working. please help me.

void Delete_Player( char *name )
{
        FILE *infp , *outfp ;
        int nor, wchfile, found = 0 ;
        Player_t P, temp ;

        infp = fopen ("PLAYERsInfo.dat","rb+");
        //outfp = fopen("Dup.dat","wb");

         if ( !infp ) {
                printf (" ( \"%s\" ) open failed \n" , "PLAYERsinfo.dat");
                return ;
        }

        while (1 == ( nor = fread (&P , sizeof ( P ), 1 , infp) ) )
        {
                if ( ! strcmp ( name , P.name ) ) {
                        found = 1 ;
                        break ;
                }
        nor++;  //fwrite ( &P , sizeof (P), 1 , outfp );
        }

        if ( feof ( infp ) )
        {
                printf("No ( \" %s \") is present \n", …
Iam3R 24 Junior Poster

You forgot the #endif The correct way of doing what? What are you trying to do?

i am trying to use conditional macro , and want to check a defined value as in line number 4.

i used #if ( fst == 1) then the code is working and if i replace the statement #if ( fst == 1) with #if fst then also the code is working .

i just want to know which one is correct and good to use.

Iam3R 24 Junior Poster
#define fst 1
int main()
{
     #if( fst ==1 )
               printf("FST\n");
     #else 
              printf("Dummy FST\n");
 return 0;
}

if i replace the statement in line 4 with #if fst also the code is working.

can any one tell me what is the correct way , advantages and disadvantages.

Iam3R 24 Junior Poster

*f is evaluated prior to moving parameters to the stack - which of course yields an address.

i dont understand the above statement;

Iam3R 24 Junior Poster

As far as my understanding and other referals i understood that when the address
of a local variable is returned the first call using this address may print the correct
value but if it is called after any other function may get undefined values.

but my program is returning the value that is equivalent to address.

please some one help me in understanding this.

int * first();
int * second();

int main()
{
	int *f, *s ;
	f = first();
	printf(" After calling first : value of f ( %p ) \n", f);
	printf(" After calling first : value of *f ( %x )\n", *f);
	s = second();
	printf(" After calling second : value of s ( %p ) \n", s);
	printf(" After calling second : value of *s ( %x )\n", *s);
	f = first();
printf(" After calling first second time : value of f ( %p ) \n", f);
printf(" After calling first second time : value of *f ( %x )\n", *f);
	return 0;
}	

int * first()
{
	int f_lcl = 0xAAAA ;
	printf("  In First  : value of f_lcl ( %x ) \n", f_lcl);
	printf(" In First : addr of f_lcl is ( %x ) \n", &f_lcl); 
	return &f_lcl ;
}

int * second()
{
	int s_lcl =  0xFFFF;
	printf(" In Second : value of s_lcl ( %x )\n", s_lcl);
	printf(" In Second : addr of s_lcl is ( %x ) \n", &s_lcl); 
	return &s_lcl ;
}

the out i …

Iam3R 24 Junior Poster

thanks gerard and NicAx64 for your answers.

Iam3R 24 Junior Poster

i just tried to check the symbol table by using foll files .


I am using the following files

Head_Symb.h

#define LV 20
extern int Glb_Var;
extern int fun( char *p , char a[]);

Lib_Symb.c

#include "Head_Symb.h"
int fun( char *p , char a[])
{
        static int Stc_Var  ;
        int Lcl_Var2;

        printf("Ptr: = %s\n", p);
        printf("Arr: = %s\n", a);
        printf(" Glb_Var = %d \n", Glb_Var);
        return 0;

}

Main_Symb.c

#include "Head_Symb.h"
#include<stdio.h>
int Glb_Var = 10;
int main( void )
{
        int Local_Var = LV;
        char *Ptr = "pointer";
        char Arr[]= "array";
        fun ( Ptr , Arr);
return 0;
}

i am using following commands

gcc -c *.c
Lib_Symb.o and Main_Symb.o are generated

when i use the command
nm Lib_Symb.o
the following are listed :

00000000 T fun
                 U Glb_Var
                 U printf
00000000 b Stc_Var.0

and

when i use the command

nm Main_Symb.o

U fun
00000000 D Glb_Var
00000000 T main

gcc *c

and when i use the command
nm
or
nm a.out

i got following list

08049628 A __bss_start
080482e4 t call_gmon_start
08049628 b completed.1
08049528 d __CTOR_END__
08049524 d __CTOR_LIST__
08049618 D __data_start
08049618 W data_start
080484a4 t __do_global_ctors_aux
08048308 t __do_global_dtors_aux
0804961c D __dso_handle
08049530 d __DTOR_END__
0804952c d __DTOR_LIST__
08049538 D _DYNAMIC
08049628 A _edata
08049630 A _end
080484c8 T _fini
08049524 A __fini_array_end
08049524 A __fini_array_start
080484e4 R _fp_hw
0804833c t frame_dummy
08048520 …
Iam3R 24 Junior Poster

Hi ,

so far i have been concentrating on programming aspects.
now its time to learn some internals of C -compiler.

Lexical Analyzer
Parser
Hashtables
Syntax Checkers
Expression Evaluators
Symbol table
:

etc

please share me some info related to symbol table

what are the contents of the symbol table
and how to view the contents of the symbol table.

i am using Gcc compiler on Linux.

Thanks

Iam3R 24 Junior Poster

i am writting a program for finding the no of keyword ( occurances ) and operators occurances.

i am taking the all the keywords in an array and all the operators in seperate arrays for each category of operators.

char *kw[] = {"auto","break"..."while" };
char *Arth_op[] = { "%","*","+","-","/"};

according to the ascii value of that characters.

and using the binary search and other support functions i am finding the occurances of all the keywords and opearators.

now the problem is, there are operators with two characters
like :

>= , <=, ++, --, ==, += -= and many

here i cannot use my bsearch function.
to find the occurance of an operators

all the keywords and operators are arranged in the array in increasing ascii value of characters for single charcater operators.

but how to handle the assignment and relational operators.

please suggest me a way to solve this problem.

or suggest me is there any other method to solve the problem.

Iam3R 24 Junior Poster

Out of curiosity, are you summarizing what you remember of the code (because it's broken), or was the code given as a "find the problems" question?

i have written what i remember.

but its not "find the problem" type , may be the question itself is wrong.

Iam3R 24 Junior Poster

Hi,

i have a doubt regarding conditional macros and undef directive.
can i use undef for a function like - macro, by just specifying the name of the macro with out specifying the argument list as written in line 8.


is the code correct with out these statements:

#define OPER(A+B) ((A) * (B))
 #endif

is the below statement correct
#if!defined(OPER)
define OPER(A+B) ((A) * (B))

i found these in one interview.

void Call( void );

#define OPER(A,B) ((A) + (B))

int main()
{
      #undef OPER;
       Call();
       return 0;
}

void Call()
{
    #if!defined(OPER)
    #define OPER(A+B) ((A) * (B))
    #endif
    int res = OPER(10,15);
    printf("res = %d \n", res);
return ;
}
Iam3R 24 Junior Poster

Yes Got it why there is no reply.

becaues there are hell lot of links provided in previous posts.

thanks all .

Iam3R 24 Junior Poster

>>why not 4 bytes.

You answered your own question in the first sentence you posted. Because 5 * sizeof(int) = 5 * 4 = 20. Simple grade-school math.

why sizeof does not consider name of the array as some address and give pointer size bytes.

Iam3R 24 Junior Poster

Hi ,

I want to write a program on Lexical Analyzer:

which finds the no of keywords, no of operators ( based on the classification arithmetic, logical,....), constants, and others.


please suggest me one good method.

i am using a method which follows as below:

char *Arith_Oper[]={ "+", "-", "*", "/", "%" };
:
:
and all other category of operators
char *KeyW[] = { "auto", "break",..... "while" };
:
:

i am using two functions
1. GetWord(); which gets a word from the file and one binary search function which
i want to use a fucntion getword which gets word from a file and this word is sent to all comaparisions to check the category and based on that that index of array is incremented and later once the all file is parsed the out put is displayed based on the count of that opearator or keyword.

i am using the Binarysearch function for finding the position of token .

but this method is not efficient as the token has to be compared with all the operators and keywords and others.

so i need a method which does in an effcient manner.


please help me.

Thanks,
Danian.

Iam3R 24 Junior Poster

how the sizeof array is the total number of elements multiped by its base data type size, when the name of the array gives only the base address.

int array [5];
       sizeof array ;

gives 20 bytes.

why not 4 bytes.

because

array = &array[0]
.
Iam3R 24 Junior Poster

Hi,
i understand merge sort & quick sort even i can write the programs but iam unable to understand its complexity.

its very easy to derive complexity equations for selection & bubble sort.

as the code is little complex & recursive nature i am unable to understand its complexity and how its n log n.


please some one provide me some easy method to understand its complexity.

considering 16 elements in the list.

selection & bubble it takes O(n2);

but quick and merge 16 * 4 = 64.

Iam3R 24 Junior Poster
#include<stdio.h>
#include<stdlib.h>

#define MAX 5
char queue[MAX][30];

int front, rear, temp;

void init()
{
	front = -1;
	rear = -1;
}

void insert()
{
	if ( rear >= MAX-1 && front == -1 )
	{
			printf("\nQueue overflow");
			return ;
	}

	temp = rear;
	rear = ( rear + 1 ) % MAX ;
	printf( "\nEnter name to be inserted :\n") ;
	scanf( "%s", queue[rear]) ;
	
}

void delete()
{
	if (front == rear || rear == -1)
		printf("\nError : Underflow");
	else {
	front = (front + 1) % MAX;
	printf("\nDeleted name from the CQ is %s",queue[front]);
	}
}

void display()
{
	int i;
	printf("\nThe queue content is :\n");
	if (front > rear)
		{
			for (i = front+1 ; i < MAX; i++)
				printf("%s\t",queue[i]);
			for (i = 0; i <= rear; i++)
				printf("%s\t",queue[i]);
		}
	else
		for (i = front +1 ; i <= rear; i++)
			printf("%s\t",queue[i]);
	printf("\n");
}

void front_rear()
{
	printf("Front = %d \n", front);
	printf("Rear = %d \n", rear);
}
	
int main()
{
	int choice;
	init();
	while(1)
	{
		printf("\nMENU\n1. Insert\n2. Delete\n3. Display\n4. Exit\n5.front_rear_pos\n");
		printf("\nYour choice = ?");
		scanf("%d",&choice);
		switch(choice)
		{
		case 1:
			insert();
			break;

		case 2:
			delete();
			break;

		case 3:
		      if (rear==front)
		         printf("\nNo elements in the list");
		   else
		           display();
		           break;

		case 4:
			exit(0);
		case 5:
			front_rear();
                                                break;

		default:
			printf("Invalid Choice");
                                                break;
		}
	}
   return 0;
}

i have written a code for circular Queue using array.

the probelm with this is :
1. when i enter all the 5 elements
the rear value is 4 …

Iam3R 24 Junior Poster

You are right -- Code::Blocks (which also uses MinGW ) doesn't produce warnings or errors on that either. VC++ 2008 Express produces a warning. I'm not familiar enough with gcc to know if there are any flags that will make that compiler produce a warning on it.

there are some flags which enables the missing of case or default or both in an out side of switch and when used with enum as case constant.

these are: gcc filename.c -Wswitch-enum warns whenever a switch statement has an index of enumarated type and lacks a "case" for one or more of the named codes of that enumeration

or simply we can use gcc filename.c -Wall

Ancient Dragon commented: Thanks :) +25
Iam3R 24 Junior Poster

initialize as

union test u;
u.f = 100.23;

i know the basic initialization of union.

my doubt is why format specifier is not able to convert it in to float value.

bcz the value stored in it is a float value.

Iam3R 24 Junior Poster
[Davis@localhost UNS]$ gcc U_bc.c
[Davis@localhost UNS]$ ./a.out
a=d i=100 f=0.000000
sizeof(u)=4
[Davis@localhost UNS]$ cat U_bc.c
int main()
{
        union test
        {
                char ch;
                float f;
                int i;
        };
//union test u={'a',21,34.65}; gives a warning excess elements
union test u={100.23};
printf("a=%c i=%d f=%f\n",u.ch,u.i,u.f);

printf("sizeof(u)=%d\n",sizeof(u));
return 0;
}

in the above program it is interpreting the float value as char & int but float value is not getting interpreted.

Iam3R 24 Junior Poster

You are right -- Code::Blocks (which also uses MinGW ) doesn't produce warnings or errors on that either. VC++ 2008 Express produces a warning. I'm not familiar enough with gcc to know if there are any flags that will make that compiler produce a warning on it.

i will check out and let you know sir.

Iam3R 24 Junior Poster

you forgot the case keyword. Your program contains millions of other errors that you need to correct -- if your compiler doesn't report them then toss out that crappy compiler and get one that actually works right.

int area(shape *s)
{
 switch(s->st)
    {
        case RECTANGLE:
            return (s->shape_u.rect.side1) * ( s->shape_u.rect.side2);
        case SQUARE:
            return (s->shape_u.squa.side) * (s->shape_u.squa.side);
        case CIRCLE:
            return (int)(s->shape_u.circ.radius * 2 * PI);
        default:
            return -1;
    }
}

yes sir , you are right.

f your compiler doesn't report them then toss out that crappy compiler and get one that actually works right.

but i am using GCC compiler.
it is not throwing any warnings or error for this.
switch with out case should be a error.