Narue 5,707 Bad Cop Team Colleague

>which we can later type cast to any data type, and with
>this we can traverse our 2 dimensional array...

Um, no. void** doesn't have the same generic properties as void*. Rather than a pointer to a pointer to an unspecified type, void** really is a pointer to void*. Which means you can't do this if function returns void**:

double **p = function( 10, 10 );

void** and double** are incompatible, whereas void* and double** would be. You want your function to return void* to get the generic pointer type, which can then be converted back to the original type:

#include <stdio.h>
#include <stdlib.h>

void *function(int row, int col)
{
  int **p = malloc ( row * sizeof *p );
  int i;

  for ( i = 0; i < row; i++ )
    p[i] = malloc( col * sizeof *p[i] );

  return p;
}

int main ( void )
{
  int **p = function ( 5, 5 );
  int i, j;

  for ( i = 0; i < 5; i++ ) {
    for ( j = 0; j < 5; j++ )
      p[i][j] = i + j;
  }

  for ( i = 0; i < 5; i++ ) {
    for ( j = 0; j < 5; j++ )
      printf ( "%-3d", p[i][j] );

    puts ( "" );
    free ( p[i] );
  }

  free ( p );

  return 0;
}

Confusing? You bet, but that's how it is.

Narue 5,707 Bad Cop Team Colleague

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

Because it adds unnecessary complexity to the grammar and as a result, the compiler. Since a language feature already exists which handles the intended function of nested comments (ie. commenting out code), proposals to add nested comments were rejected.

>why compiler implementers/preprocessor implementers
>have not handled such a simple situation .

Just because you think it's a simple situation doesn't make it so. Implementations are welcome to support nested comments as an extension, or (more commonly) recognize the error and throw a warning. But nested comments weren't valuable enough to make it through the standardization process.

It's not especially difficult to implement nested comments, assuming they're supported. For example, each comment symbol can maintain a level count which is incremented on entering a comment and decremented on exiting a comment. Everything between two comment symbols with a level of 0 would be removed during the comment removal phase.

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

Zero initialization was deemed too expensive to be the default behavior. You'll find a lot of things in C have that rationale.

>when an array is initialized partially why it initializes remainig elements to zero.
Automatic variables aren't initialized, but that's only a single object and easy to manage. However, partial initialization of …

jephthah commented: nice +7
Iam3R commented: Thanks +1
Narue 5,707 Bad Cop Team Colleague

>a.) You mean square root of N?
Assuming you're talking about my "O(# of powers of 2 below n)" estimate, no, I really do mean powers of 2. The square root of N is close at first (but not quite right), and it gets worse as N grows.

>f.) As far as I understand... shouldn't it be O(N*N^3) = O(N^4)?
Let's take a look:

for( i = 0; i < n; i++) {
  for( j = 0; j < n * n; j++) {
    for( k = 0; k < j; k++)
      count++;
  }
}

The i loop is O(N), no need to explain why. ;) The j loop is O(N^2) as explained earlier in the thread. The k loop is an instance of taking the upper bound. To get the complexity of the k loop, you choose the largest value that k would reach before the loop ends, which in this case would be the j loop's upper bound: n*n.

So, you've got an O(N^2) loop inside another O(N^2) loop inside an O(N) loop. The k loop isn't quadratic the whole time, but that's the upper bound, so we'll call it O(N^2). Put it all together and you get O(N^5).

>g.) And this one... O(N^4) as well?

for ( i = 0; i < n * n; i++) {
  for (j = 0; j < i; j++) {
    for ( k = 0; k < j; k++)
      count++;
  }
}

The i …

Nick Evan commented: Excellent posts in this thread +12
Narue 5,707 Bad Cop Team Colleague

>Is this all correct? return 0 from main means success. If the system treats 0 as an error status, the implementation must convert it to a suitable success value to be conforming.

Narue 5,707 Bad Cop Team Colleague

>which one is the correct one to use, what is the problem with others.
They're all correct in certain situations, but one is unconditionally correct:

int main(void)
{
  return 0;
}

Let's go from top down.

main() { }

This definition won't compile under C99 because implicit int was removed. C89 doesn't support an implicit return from main, so falling off the end is undefined behavior. Finally, because there's no prototype someone can call it with more than zero arguments legally:

/* Won't compile as C99: no return type */
main()
{
  main(1, 2, 3); /* OK: no prototype */
  /* Undefined behavior: no return */
}
void main() { }

This definition is undefined behavior if the compiler doesn't support void main. Lack of a prototype (the empty parameter list doesn't mean "no arguments" in C) means that main can be called with an unexpected number of arguments.

int main() { }

In C99 this definition is correct, but lack of a prototype can still cause problems with recursive calls. Note that calling main recursively is not the best practice to begin with. ;)

int main() { return 0; }

This definition is correct across the board, but the lack of a prototype issue still exists.

Iam3R commented: Thank you +1
Narue 5,707 Bad Cop Team Colleague

>it casted the timespan asd but it gives me more errors, can anyone please help me?
Maybe you should look at your monitor through a mirror, because you seem to be naturally backwards.

Narue 5,707 Bad Cop Team Colleague

>Please guide me so as i can check if the password value in
>the database is same as the one entered in the text box.

Send the one entered in the text box to a stored procedure which checks for matches against the selected user.

>I have no idea how to print
Booya.

Narue 5,707 Bad Cop Team Colleague

>The tab key doesn't take you to it, however. It most definitely should.
Good suggestion, that's basic login box design. Though you might want to consider choosing the option to remain logged in if it bothers you that much.

>Only after submitting is it made clear that you have to join first.
I haven't seen any serious forums that allowed guests to post in a long time. Perhaps you need to upgrade your common sense module. :)

>3. Pop-ups. Need I say more?
Yes, you do. Are you talking about ads or stuff like the questionnaire? In the former case, Dani has generally been good about bitching to the ad hosts when they try to pull that stuff. The questionnaire may be annoying...once. I haven't seen or heard about any other exceptional pop-ups beyond that.

>4. Is it me, or do your adverts make your site particularly slow?
The site makes the site particularly slow. The ads make it worse. Get yourself something like Adblock Plus and you can make the site usable.

>5. Now it won't let me create the tags I want.
You seem stuck in the 90s where forumgoers didn't need to create an account, so why even bother with tags? :D Personally, I find them distracting anyway.

Narue 5,707 Bad Cop Team Colleague

>Do not use carriage return in portable code.
>b) Initializer lists with objects will not work with all compilers

Alright, I let the carriage return advice slide, but now you're being too cryptic for useful advice. Give specifics and examples, please.

Narue 5,707 Bad Cop Team Colleague

Your first example is a syntax error because it's neither a method nor a property. If you add a parameter list, it works and becomes a method:

public int ShiftsLeft() {
  return shiftsToWork - shiftsWorked;
}

>Can someone tell me the difference between the two
Methods are named executable blocks of code that take a predetermined number and type of parameters and return a single value (possibly of type void). Properties are a controlled interface around (typically) a single class field. Let's look at it from the perspective of a lack of properties:

class Test {
  private int _field;
}

Let's say you want to give public access to _field, but you still want _field itself to be private. Unrestricted access could break your class' assumptions about that field. For the sake of argument, say the value of _field should be in the range of [0,100).

In the absence of properties, one might use methods for the interface:

class Test {
  private int _field;

  public int GetField() { return _field; }
  public void SetField(int value)
  {
    if (0 <= _field && _field < 100) {
      _field = value;
    }
  }
}

Then callers can access _field through the restricted interface and all is well, yes?

Test foo = new Test();

foo.SetField(55);
Console.WriteLine(foo.GetField());
foo.SetField(10000);
Console.WriteLine(foo.GetField());

The syntax is kind of awkward, but it's not horrible. Properties are simply another way to do the same thing with a more intuitive syntax:

class Test {
  private …
apegram commented: Excellent lexplanation. +1
JohnnyT commented: A superb explaination and it really helped me out. Thanks +6
Narue 5,707 Bad Cop Team Colleague

>but why the variable number_value is 0.
>I expect the value of 7.

Deep under the hood (for g++), number_value is getting set to 0.0 because the "a" is read as a floating-point value and fails to be converted by strtod, which returns 0 if no conversion can be made. Essentially g++ uses a reference to number_value as the working result throughout the process.

On the other hand (to explain vmanes' results), Visual Studio uses a temporary local variable to perform the conversion and only sets the reference to number_value on a successful conversion.

In this case, Visual Studio is correct and g++ is not because these conversions are performed through the num_get facet, which is required to leave the value reference unchanged on failure. g++ doesn't meet that requirement.

yapkm01, it would help to know what compiler you're using. For that lack, my answers are based on the two compilers vmanes tested with.

vmanes commented: Nice explanation of the behind the scenes actions +5
Narue 5,707 Bad Cop Team Colleague

>please give me the "C" language code for reversing a two dimensional character array.
No, piss off. We don't do homework for lazy students.

>Please its very urgent.
I feel no sense of urgency. In fact, I'm quite content with watching you slowly come to the realization that you're going to fail the class. :)

Narue 5,707 Bad Cop Team Colleague

>I want to limit the amount of characters used to 10.
Note the difference between limiting the number of characters used and limiting the number of characters the user can type. The latter is rarely needed, requires excessive work on your part to simulate shell input, and is guaranteed to be non-portable.

With fgets, or some other method that limits the number of characters extracted from the stream, it doesn't matter how much the user types. You can limit the number of characters used to whatever you want without resorting to non-portable code.

>can you please tell me which way it is safer?
Without the field width, scanf is no better than gets in terms of risk for buffer overflow. However, your use of scanf was perfectly safe. Though one thing to keep in mind is the difference between the field width in scanf and the buffer size limit in fgets:

scanf("%5s", a); /* Reads up to 5 characters, then appends '\0' */
fgets(a, 5, in); /* Reads up to 4 characters, then appends '\0' */

fgets assumes the size limit includes space for the terminating null character while scanf assumes the field width refers to actual characters in the stream. This is a ripe location for an off-by-one error.

Narue 5,707 Bad Cop Team Colleague

>bump
Well well well, you must be the lord and master of the universe to push all of the other threads down and give yours immediate priority. Did it not occur to you that bumping is rude? How about that those of us who could easily help you right now will choose to ignore you simply because of the bump? No? Well, now you have something to think about while you wait...again.

Narue 5,707 Bad Cop Team Colleague

>the error might be here ...
It might.

>new_student->name = (char *)malloc(8 * sizeof(char));
You allocate memory to name, all is well so far (barring minor nits).

>new_student->name = "Michael\0";
Bzzt! You've now overwritten your only reference to the memory just allocated. Not only is this a memory leak, if you call free on a pointer that wasn't returned by malloc and friends, bad things happen. You probably want to use strcpy to copy the contents of that string literal into name.

It should go without saying that this bug is repeated several times and you should address each instance rather than just name. I used name as the example.

Narue 5,707 Bad Cop Team Colleague

Double the brace up:

Console.WriteLine("{0} ... {{", var1);

MSDN clearly states what happens in the format string:

Opening and closing braces are interpreted as starting and ending a format item. Consequently, you must use an escape sequence to display a literal opening brace or closing brace. Specify two opening braces ("{{") in the fixed text to display one opening brace ("{"), or two closing braces ("}}") to display one closing brace ("}"). Braces in a format item are interpreted sequentially in the order they are encountered. Interpreting nested braces is not supported.

Salem commented: And the RTM award goes to..... :) +19
ddanbe commented: This is what discerns a pro from a learner like me :) +6
Narue 5,707 Bad Cop Team Colleague

>Any suggestions?
I have two suggestions:

  1. Oh my god, don't manually write out 160 text boxes! Every class derived from Control has a Controls property that lists out all of the controls contained by that control. If you have a form and 160 text boxes directly on that form, you can loop through formName.Controls to get the text boxes (like in my example).
  2. StreamWriter.Write isn't magic. On top of being the wrong overload, how are you going to tell Write to add a newline every 16 characters? Please read the documentation on methods before trying to use them. At least then you'll have a chance at getting it right.
GAME commented: Wouldn't answer my question. +0
kvprajapati commented: Good suggestions +8
Narue 5,707 Bad Cop Team Colleague

>I just can't figure out how it is supposed to be implement
>with the extra array element structure in the middle.

It's just an array of linked lists:

struct Hotel {
  std::string name;
  LinkedList<Attendee> attendees;
};

Hotel hotels[5];
for (int i = 0; i < 5; i++) {
  std::cout<< hotels[i] <<'\n';

  Attendee::iterator it = hotels[i].attendees.begin();

  while (it != hotels[i].attendees.end()) {
    std::cout<< *it++ <<'\n';
  }
}
Narue 5,707 Bad Cop Team Colleague

>I want to order the ParentList so the Chromosome Class with the
>smallest value is at the top and the one with the highest is at the bottom.

Okay, that's completely different. Note that C# already has something called attributes that aren't the same thing as class fields or properties. And you have a list of objects, not a list of classes. Accurate terminology goes a long way toward not confusing people. :)

Anyway, you want something more like this:

using System;
using System.Collections.Generic;

namespace JSW
{
    static class Program
    {
        static void Main()
        {
            var chromosomes = new List<Chromosome>();
            Random rand = new Random();

            for (int i = 0; i < 10; i++)
            {
                chromosomes.Add(new Chromosome(rand.Next(100)));
            }

            chromosomes.ForEach(x => Console.WriteLine(x.Punishment));
            Console.WriteLine();

            // This call to sort is the part you're interested in
            chromosomes.Sort(
                delegate(Chromosome x, Chromosome y)
                {
                    return x.Punishment - y.Punishment;
                });

            chromosomes.ForEach(x => Console.WriteLine(x.Punishment));
        }
    }

    class Chromosome
    {
        public int Punishment { get; set; }

        public Chromosome(int punishment)
        {
            Punishment = punishment;
        }
    };
}

If you're a beginner then you probably want to read up on delegates and anonymous methods/lambdas to fully understand everything in the example.

apegram commented: Finally, someone showing LINQ, extension methods, and delegates. It's rare around here. +1
Narue 5,707 Bad Cop Team Colleague

>int[] nbrs = new int[balls];
This (line 11) declares a local variable in your constructor that hides the class field. You initialize the local array, but the class field remains null. Change it to this:

nbrs = new int[balls];
Narue 5,707 Bad Cop Team Colleague

You didn't do any research did you? On top of being pretty freaking easy if you know XSLT or basic XML processing in .NET, a simple search on google gives you complete solutions.

Narue 5,707 Bad Cop Team Colleague

Well, how you do it depends on a few things that you didn't specify, so I'll just throw out one possible solution to get your creative juices flowing:

using System;
using System.Linq;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;

namespace JSW
{
    static class Program
    {
        static void Main()
        {
            List<Type> classes = new List<Type>(
                new Type[] { typeof(Foo), typeof(Bar), typeof(Baz) });

            classes.ForEach(c => Console.WriteLine(c));
            Console.WriteLine();

            var sorted = classes.OrderBy(c => GetDescription(c)).ToList();

            sorted.ForEach(c => Console.WriteLine(c));
        }

        static string GetDescription(Type type)
        {
            Attribute[] attributes = Attribute.GetCustomAttributes(type);
            var descr = (DescriptionAttribute)attributes.SingleOrDefault(
                attr => attr is DescriptionAttribute);

            return descr != null ? descr.Description : "(no description)";
        }
    }

    [Description("B")]
    class Foo { }

    [Description("A")]
    class Bar { }

    [Description("D")]
    class Baz { }
}
Narue 5,707 Bad Cop Team Colleague

>Ive never used XNA before,
So you have no business making any claims about it, much less the people who use it.

>It kinda pisses me off.
What a stupid post. I can only conclude that you feel threatened by the competition these easy to use APIs bring to the table and took the low road of cutting down others instead of rising to the challenge. Not cool.

A wise man welcomes competition and betters himself, a fool stomps it out so his mediocrity shines.

Narue 5,707 Bad Cop Team Colleague

>square root of N... N loglogN... N log^2 N... N^2 log N...
>and many more. How do I know how those look like?

They're generally not as clear cut as N and N^2 because you typically don't see this kind of loop directly:

for (int i = 0; i < n; i++) {
  for (int j = 0; j < log10(n); j++) {
    // ...
  }
}

Obviously it's O(N logN), but usually you need to look a little deeper. For example:

for (int i = 0; i < n; i++) {
  bst.insert(load_value());
}

This is O(N logN) as well because the insert algorithm for the binary search tree is assumed to be logarithmic. It's really the same thing, but not as obvious. Simple loops are used to convey the idea of growth because it's easy to illustrate.

>Also with divide and conquer algorithms... you can divide a problem to N/2. How?
Binary search is the quintessential example of divide and conquer. The idea is to minimize your working set. In the case of binary search, this is immediately obvious: using the value, you can lop off half the set with a single test.

For something like quicksort it's less obvious, but the principle is the same. Divide the working set in half so that you're sorting two smaller sets. The benefits are twofold:

  1. It's faster to sort two small sets than one big one, or four small sets than two big …
jonsca commented: "people PhDs" -- you crack me up. :) +2
Ajantis commented: Narue has explained Big-Oh in a simple and comprehendable way +2
Narue 5,707 Bad Cop Team Colleague

You realize that the >> operator for input is is default delimited on whitespace, right?

Narue 5,707 Bad Cop Team Colleague

>Now let’s check out what will be the disadvantage of _alloca over new/malloc :-
>1) One has to be cautious while using alloca for huge blocks.
>2) Its scope is limited to a function call.
>3) As stack overflow is not a standard C++ exception, one hast to use structured exception handling for it.

You missed one: _alloca is specific to the Visual Studio runtime library, and any safe use of it requires one to delve into structured exception handling. Translation: Your code's portability is hosed.

Other implementations support some form of alloca, but experience has taught us that it should be avoided[1]. The stack size is an unknown quantity without hurting portability, and the whole point of dynamic allocation is to handle an unpredictable variation of block sizes. Thus, the very nature of alloca promotes brittle software.

>NOTE:- I have added hyperlink in accordance to rule, which says :-
>"Self-promotion links are permitted within forum signatures provided
>they do not contradict with any other sitewide rules, such as
>inappropriate language or content." So is it ok?

Note that "signature" means the signature feature in the control panel. When you set a signature, that signature is applied to all of your posts. In this case, you've created a "fake" signature by typing what you want into the post itself, so it doesn't fall under the self-promotion clause.

[1] Amazingly enough, C99's VLAs are a language-blessed alloca with all of …

Narue 5,707 Bad Cop Team Colleague

>Compilers are free to make them any size they want.
Within limits. A long integer in C is absolutely required to be at least 32 bits, so as long as you you can ignore the bits of a larger size, you're solid. C99 introduces the <stdint.h> header where exact-size types are supported (int32_t in this case), if you need an exact type, it's probably a good reason to jump to C99. Otherwise you need to do what we did before: create a typedef and treat it as a non-portable aspect of the code.

Narue 5,707 Bad Cop Team Colleague

>What makes you think Narue is female?
Indeed. It's all well and good to take someone at their word online, there are a lot of liars out there. I could be one of them. ;)

>Don't make me rethink my entire worldview.
Try this one for size: I'm a pimply faced teenage dude who gets bullied at school, Tom is a recovering Kathy Sierra, jephtha is when I get drunk on my parent's booze (when they're not home, because I'd get in trouble), and Dani is Al Gore.

jephthah commented: LOLerskates +0
Narue 5,707 Bad Cop Team Colleague

>D.resize(3, temp);
Well that's wrong, and it shouldn't even compile. temp is an array of double and that particular overload of resize takes a value of type T (that the vector was declared with). Since T is double, it's a type mismatch.

>F.resize(3, temp);
This is equally wrong for the same reason. vector<double> isn't compatible with an array of double.

>void do(vector<double> & F);
Now I'm sure that you're paraphrasing rather than posting actual code. do is a freaking keyword in C++!

Your questions can't be properly answered until you give us something valid to work with. You can do what you're asking in C++ (and in C), but not that way.

Narue 5,707 Bad Cop Team Colleague

>when should i use "return 0;" at the end of a main() function?
Always or never, depending on your preference and whether or not you're writing standard C++. In standard C++ 0 is returned automagically when execution falls off the end of main, so the following is perfectly valid:

int main()
{
}

However, some people like to be consistent and explicitly return from any function that doesn't return void:

int main()
{
  return 0;
}

My personal preference is that if I have multiple returns from main, EXIT_SUCCESS is always explicit at the end, but otherwise I omit the return statement entirely:

int main()
{
  // Stuff with no return statement
}
#include <cstdlib>

int main()
{
  // Stuff

  if ( failed )
    return EXIT_FAILURE;

  // Stuff

  return EXIT_SUCCESS;
}
tkud commented: Nicely said. +0
Narue 5,707 Bad Cop Team Colleague

>scanf() is a crappy function that does crappy things to
>the program. Get over it and use functions that actually work.

scanf works just fine. The problem is ignorant programmers who don't understand the rationale behind it. Calling scanf crappy after trying to read interactive input is much like calling fgets crappy because you didn't check for long lines.

Dave Sinkula commented: Yeah, that's always a point to make. It just seems that the fgets/s... stuff more easily gets rid of 99% of the issues (with a fair-sized buffer). The scanf versions seem at least has difficult if not moreso. +13
Narue 5,707 Bad Cop Team Colleague

>when i run the program i got the same out put by using memcpy and memmove
There's nothing stopping an implementation from implementing memcpy in terms of memmove. Further, calling memcpy on overlapping memory invokes undefined behavior. It may or may not fail.

>what is meant by moving memory and how its safe. why memcpy is dangerous.
memcpy does a mindless copy, regardless of whether there are shared bytes between the source and destination:

void *memcpy (void *dst, const void *src, size_t n)
{
  char *a = dst;
  const char *b = src;

  while (n--)
    *a++ = *b++;

  return dst;
}

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:

void *memmove(void *dst, const void *src, size_t n)
{
  char *a = dst;
  const char *b = …
Salem commented: Nice +19
Ancient Dragon commented: Very good explanation. +26
Narue 5,707 Bad Cop Team Colleague

>I'm well aware that I need to find greener pastures
Keep in mind that it takes a lot of shit to keep those pastures green. ;)

Narue 5,707 Bad Cop Team Colleague

>Nobody twisting your arm to click on the thread, is there?
In theory, excessive posts could fill up the database and slow the site down enough to cost Dani more money in maintaining the status quo, and in turn she could start charging subscriptions. Every "I HAZ XXX POSTS D00D!!11" brings Daniweb closer to death by placing greater burden on the system without any value to the community.

jonsca commented: LOL. Oh wait, you're serious.... :P +0
Narue 5,707 Bad Cop Team Colleague

>Its urgent
For future reference, stating that your problem is urgent will likely be counterproductive. A lot of us are perverse enough to ignore you solely because you're in a rush.

Anyway, the immediate problem is your word counting logic isn't a part of the loop. That's not a very effective state machine. ;) Compare and contrast:

while ((cur = fgetc(fp1)) != EOF)
{
    if (cur != '\n')
        ++countCh;
    else
        ++countLn;

    if (Space)
        word = 'O';
    else
    {
        if (word == 'O')
        {
            ++countWd;
            word = 'I';
        }
    }
}
Narue 5,707 Bad Cop Team Colleague

>// user is not allowed to create arrays with more than 10 symbols
Okay.

>cin>>s;
Oops, too late. There's nothing stopping the user from typing more than ten characters. You can check for a string length of ten or less, but by then any damage has already been done. You can fix it by only storing ten characters, regardless of how much the user types:

cin>> setw(10) >> s;

>Would be great if someone could point me in the right direction.
Assign cpt to s, then add half the length of the string to cpt. Now you can walk backward until cpt is equal to s.

Narue 5,707 Bad Cop Team Colleague

>try explaining me what to do or give me a code for example
You could look at any of the open source libraries that do what you want for ideas on how to write your own implementation.

>don't redirect me to a site that already made a library for
>this because you only wasted your time telling me that

With your attitude, I think telling you what to do or giving you example code would be more of a waste of time. I try not to give proper help to people who don't deserve it.

NathanOliver commented: unfortunatly they wont +1
Narue 5,707 Bad Cop Team Colleague

>how can this be taken care of?
You have no choice but to allocate a new block of memory. Since str is a local array but needs a longer lifetime, you can replace it with dynamic memory:

char* foo (int ch) {
  char* str = malloc(10);

  if (!foo1(str, ch))
    strcpy(str, "???");

  return(str);
}

But that requires the calling code to call free as well (a step often forgotten). A usually better alternative is to pass the buffer in as a parameter. That way the calling code owns it and can decide how to manage the memory:

char* foo (char* str, int ch) {
  if (!foo1(str, ch))
    strcpy(str, "???");

  return(str);
}
Narue 5,707 Bad Cop Team Colleague

>Will pay money for doing the assignment.
No, cheater. Piss off.

>can u give me the codes...
No, cheater. Piss off.

Narue 5,707 Bad Cop Team Colleague

Put it in the list of startup applications on installation.

Narue 5,707 Bad Cop Team Colleague

>And can anyone add any more essential property?
No, nobody can add more than the standard itself without entering the realm of implementation-defined and undefined behavior. If you don't understand the standard, specify which parts and I'll help you interpret it. But that particular section (12.6, IIRC) is very lucid, in my opinion.

>I have a C# standard & its harder than Shakespears texts to read! |-:
Standards are like that. You get used to it.

Narue 5,707 Bad Cop Team Colleague

>So you mean it have nothing to do with human readable part.
Pretty much. We're talking about individual tokens such as operators, numbers, identifiers, etc... The parser should simply be able to take a token and work with it rather than try to recognize what it represents first.

Narue 5,707 Bad Cop Team Colleague

Grab a draft of the C++ standard (google is your friend) and search for "Temporary objects".

Narue 5,707 Bad Cop Team Colleague

The lexer turns source code into something that's easier to parse. That's really all there is to it. ;)

Narue 5,707 Bad Cop Team Colleague

Works for me:

#include <stdio.h>
#include <time.h>

int main(void)
{
  time_t t = time(NULL);
  struct tm *now = localtime(&t);

  printf("Day of the year: %d\n", now->tm_yday);

  return 0;
}

Output (for Feb 15th, 2010, EST):

Day of the year: 45

What was your "incorrect number"?

Narue 5,707 Bad Cop Team Colleague

>else if (weight >= 100 & < 200)
"else if weight is greater than or equal to 100 and less than 200". That makes perfect sense, but it's wrong. C++ won't infer that in the second half of the expression you're still trying to compare with weight. Further, & is the bitwise AND operator, not the logical AND:

else if (weight >= 100 && weight < 200)

Apply that to the other clauses and see how you fare.

JHus00 commented: Thanks +1
Narue 5,707 Bad Cop Team Colleague

Sounds like homework questions. How about you come up with at least one reasonable answer to each and we'll tell you if they make sense and possibly offer more.

Narue 5,707 Bad Cop Team Colleague

>printf("Enter Input : ");
The stream isn't guaranteed to be flushed unless you print a newline or call fflush. The user may not see your prompt before fgets starts blocking, which is generally very confusing. ;)

>while(i < length)
You only use for this loop, yet it's declared at the top of main. Wouldn't it be easier to read the code if your variables are declared closer to where they're used? Further, your while loop is constructed identically to a for loop, so I'd say a for loop makes more sense here.

>if(input < 48 || input > 56)
The world is not ASCII. You can make your code portable by using '0' and '9' instead.

>return 0;
>break;

The break is redundant; it'll never be reached because you return on the previous line.

>converted_number = converted_number*10 + (input - 48);
Once again, '0' makes the code portable.

Narue 5,707 Bad Cop Team Colleague

>Can you give me an example as to where this error occurs?
Actual stream errors are rare, but end-of-file isn't, even for interactive input. Both are possible, and your code should take that into account.

Narue 5,707 Bad Cop Team Colleague

>fgets(usercheck,256,stdin);
Don't forget to check for failure. The last thing you want to do is dereference a null pointer on the next line.

>usercheck[strlen(usercheck) - 1] = '\0';
While this covers the average case, it's possible for fgets to succeed yet not end with a newline. Unless you want an edge case bug where a legitimate character is deleted, you should check for the presence of a newline first:

if (fgets(usercheck, sizeof usercheck, stdin) != NULL) {
  char *newline = strchr(usercheck, '\n');

  if (newline != NULL)
    *newline = '\0';

  /* ... */
}

On a side note, though it's a less efficient method and more obscure than the one above, I like the one-liner of strcspn:

if (fgets(usercheck, sizeof usercheck, stdin) != NULL) {
  usercheck[strcspn(usercheck, "\n")] = '\0';

  /* ... */
}