~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Yes its working thanks a lot to all the guys at the forum.

>> remove the 'char *' -- it is hiding the other variable
Just wanted to know wat is the meanig of this stmt

I thought that i would post the working and clean code so that someone can refer to this for learing the string legth funcitons.

#include <stdio.h>
#include <stdlib.h>
 
int strlength ( char input[] )
{
  int count = 0;
  while ( input[count] != '\0' )
    ++count;
  return count;
}
 
int main(void)
{
  int ch, index = 0;
  char *input = 0;
  char inputBuffer;
 
  while ((ch = getchar()) != '\n' && ch != EOF);
  fputs ("Enter some text: ", stdout);
  while ((inputBuffer = getchar()) != '\n')
  {
   input = (char*) realloc (input, index + 2);
   if (input == NULL)
   {
    fputs("Memory allocation error", stderr);
    exit(1);
   }
   else
   {
 
   input[index++] = inputBuffer;
   }
  }
  input[index] = '\0';
  printf("The length of the string is %d", strlen(input));
  return 0;
}

Thanks again Narue and Dragon.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

>>meaning of memory leak
it occurs when you use one of the functions that allocate memory, such as malloc() then do not free the memory before using the pointer again. In the code you posted, pointer variable s was allocated over and over without ever freeing the memory. You should have called realloc() instead of malloc() so that the memory block would have been expanded.

But when we end the program the memory is automatically returned to the OS for its use and the prog in the end uses the same mem. it was about to use so why the realloc instead of malloc.

Even then i have heeded your advices and rewritten the code.
I even read the tutorials concering the disadvantages of scanf and gets and also flushed the stream buffer before takin input.

It compiles welll but jumps out during execution ie runtime error. The updated code is as follows :

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

// function for evaluating string length

int strlength ( char input[] )
{
  int count = 0;
  while ( input[count] != '\0' )
    ++count;
  return count;
}

int main(void)
{
  int ch, index = 0;
  char *input = 0;
  char inputBuffer;
 
 // procedure for bypassing the junk in stream
  
  while ((ch = getchar()) != '\n' && ch != EOF);
  fputs ("Enter some text: ", stdout);
  while ((inputBuffer = getchar()) != '/n')
  {
 
   //reallocating taking in consideration the '\0'

   char* input = (char*) realloc (input, index + 2); …
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Thanks a lot for all your help but let me get one thing straight.

No, I don't do homework for anyone.

Friend, neither do i approve of the person who does it. By saying that can you write a code i meant that couldsomeone help me write a code.

I know that, but after all its only a homework

No friend this is not a homework and i never did mention so, this is just a program i have written to improve my understanding.

>> s = malloc(sizeof(char));
This just allocates one character, causing a 1 byte memory leak on every loop iteration.
>> s[index] = inputBuffer;
Since the malloc allocates only one character, this line will just scribble all over memory and most likely cause your program to crash big-time.

@AncientDragon

Can you please explain the meaning of memory leak on each iterationand the scribbling on the memory. I am totally new to such memory concepts and i have run the prog and it is giving the correct output no junk value so how do we know that it is scribbling.


@Miss Narue

>printf("The length of this string is %d", strlength(s));
This is a guaranteed buffer overflow because you don't terminate the string with '\0'.

using printf this way causes buffer overflow ???

But i have modifed the prog a bit and its workin for strings.

int main ( )
{
 char* s = 0;
 char inputBuffer, …
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Here is the code i have written to accept string from the user.
Can you please modify the code so as it can even count the space as well as print the whole line with the spaces instead of the first word.

Thanks a lot.

#include <stdio.h>
#include <assert.h>
#include <malloc.h>
#include <conio.h>
int strlength (char input[])
{
 int count = 0;
 while (input[count++] != '\0');
 return count;
}

main ( )
{
 char* s = 0;
 char inputBuffer;
 int index = 0;
 printf("\nEnter the name u want to enter : ");
 while ((inputBuffer = getchar()) != '#') // some termintaing cond.
 {
  s = malloc(sizeof(char));
  s[index] = inputBuffer;
 }
 
 printf("The length of this string is %d", strlength(s));
 printf("\n");
 
}
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

That only generates 99 numbers. You should have "i<100".

Nope i think it is alright since he has initially assigned the first element of the array with the value from cin >> array[0]; and the remainig 1 to 99 elemets get assigned values from the statement

for (int i=0; i<99; i++)
    array[i+1] *= array[i] ;

Hope i am right.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

I added some stuff and it blows up after I enter the 5th person. Sorry to be nagging but I am just lost. I have been going through the tutorials today and still a little lost. I appreciate the help I have got so far though. Not sure it's my display that is blowing it up or if it's the program.

Here is the workin prog. I hope it helps.

#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[]) {
    // declare variables
    string firstName[5];
    string lastName[5];
    double sales[5];
    double totalSales = 0.0;
    double bonus[ 5 ] = { 0 };
    double avgsales = 0.0;
    // Read in the Names, and weekly sales
    for ( int i = 0 ; i < 5 ; i++) {
        cout << "Enter the First Name ";
        cin >> firstName[i];
        cout << "Enter the Last Name ";
        cin >> lastName[i];
        cout << "Enter the Weekly Sales ";
        cin >> sales[i];
        totalSales += sales[i];
    }

    avgsales = totalSales / 5.0;
    for (int i=0; i < 5; i++) {
        if ( sales[i] > avgsales ) {
            bonus[i] = sales[i] * 0.05;
        }
        else {
            bonus[i] = 0;
        }
    }
    // Display
    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);
    cout << "\n\n Sales Report\n\n";
    cout << " First Last Total Sales Bonus \n";
    for (int j = 0; j < 5; ++j) {
        cout.width(15);
        cout << firstName[j];
        cout.width(10);
        cout << lastName[j];
        cout.width(10);
        cout << sales[j];
        cout.width(20);
        cout << bonus[j];
        cout << endl;
    }
return 0;
}
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Yes. Perl, Python, and Ruby all have good string handling abilities. Python's not really based on Perl, though.

Well talking about python as we all know that it has all the qualities that good prgg. lang. should have and is the amalgum of all the best features or the famous langs.

Python can be used for web prgg., as a scripting lang in games, also for development of games (Freedom force by Sierra) and in extensive mathematical intensive fields (used by NASA).

SO y does it not replace all the langs. existing and rule the world.
Why is C++ so powerful and famous when even Python can offer all the features and much more?

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

c++ has strong string handling capabilities.

Well as far as i know Python also has real good string handling capabilities and i guarantee far better than C or C++ since it is somewhat based on the concepts of PERL. (is it?)

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

No point in learning OpenGL and Direct X since they are extensively for Engine Developers which is i hope wat u dont want to be since it requires ground breakin concetps and requires years of work before you can make your own engine.

Better use 3rd party game engines like OGRE or Irrlicht.
Though it involves learning the 3rd party syntax, it will spare you of all the hard work. (image writng a 1000 LOC code just to read and display a Image file).

Many Indie developers use such libraries.
So if your concepts are strong and you just want to dive in game progg. 3rd party libraries are for you.

For more details if you are intrested PM me.

Hope it helped.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Hello to all progg. out there.
The sample prog. i have written is of which i am facing three doubts :

char *someFun1()
{
char temp[ ] = "string";
return temp;
}
char *someFun2()
{
char temp[ ] = {'s', 't','r','i','n','g'};
return temp;
}
int main()
{
puts(someFun1());
puts(someFun2());
}

I) Its gives the warning that The function returns the addr. of a local variable Can anyone explain the logic behind this?

II) replacing the char temp[] = {'s', 't', 'r', 'i', 'n', 'g'} with ptr char* temp = {'s', 't', 'r', 'i', 'n', 'g'} makes the prog jump out.

What is the prob i am facing here?

III) What is the difference between char temp[] = {'s', 't', 'r', 'i', 'n', 'g'} char temp[] = {"string"} Thanks for your help in advance.
Eagerly waiting for your reply.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Yup. They definitely don't use 64-bit + data types that's for sure.

For example if I wanted to multiply 3454534589384989347697547865478672934875 by 237485748375943794857937485739485793847582983478734873847837487485. It would be better to read both inputs in a chars. That's what I mean.

Hmm.. sorry for asking this stupid question but how will you read both input as characters. Can you please explain in detail as my concepts are a bit fuzzy.

Also i had got stuck with a question whose answer i could not find out how it came. The question is

// find the output
 
main()
{
[LEFT]int i = 258;
int *iPtr = &i;
printf("%d %d", *((char*)iPtr), *((char*)iPtr+1) );
}[/LEFT]
 
[I][B]// Answer:
[/B][/I]
// 2   1
// ? can you explain how this output came.

Sorry if i have bothered you a lot and if this question is off the topic you can flame me and ask me to post in a seperate thread.

Thanks for all your valuable time.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Try it, it should work.

If your sole interest to to compute large factorials then that should be fine and dandy. Like all big num libraries they don't rely on massive 64-bit+ data types.

It uses chars.

So do u imply that all the big shot math libraries use chars to execute the complex operataions with numbers?

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

This should work in c for big factorials.
.......

LOLZ wat is this beast? I dont think i am that expert in C to figure out the plethora of #defines.

Anyways you were talkin of some libraries, do you know any?

Thanks for your reply.

@WolfPack

Can you please tell me which compiler are you using :cry: ?

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Why would you wanna cast it as a long double anyway?
If you wanna find big factorials use a big number library.

Any suggestions? Thanks for your reply.

The C code works for me. Output for input 3 is 6.0000

*Damn* Which compiler are u using anyways coz i am using GNU gcc complier.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

In code in C language try to use %lf instred %Lf.
Conversion for long double is %lf.

Have already tried all the scanf identifiers (including %lf, %d,&le ..) the program just gives a wierd output.

Please run the both the programs and you will urelf know wat i am trying to say.

Anyways thanks for the answer.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Hello to all coders out there.

I have a doubt regarding the format "long double" which is producing wierd results when used in the case of a factorial program.

When "long double" used with C lang. produces the output

input = 3
factorial = -2.000000

while when used with C++ gives

input = 3
factorial = 6

So does it imply that long double doesnt work or is not supported by C and only by C++.

Thanks in advance for your help.

The programs in both lang. are given below

// code in C lang
#include <stdio.h>

long double factorial (int input) {
    long double result = 1;
    while (input) {
        result *= input--;
    }
    return result;
}
 
int main() {
    int input = 1;
    long double result = 0;
    printf("\nEnter the number whose factorial you want :  ");
    scanf("%d", &input);
    result = factorial(input);
    printf("\nThe factorial of %d is %Lf", input, result);
    return 0;
}
// In C++ lang.
 
#include <iostream>
using namespace std;
long double factorial (int input) {
    long double result = 1;
    while (input) {
        result *= input--;
    }
    return result;
}
int main() {
    int input;
    long double result = 0;
    cout<<"\nyoEnter the number whose factorial you want :  ";
    cin>>input;
    result = factorial(input);
    cout<<"\nThe factorial of "<<input<<" is "<<result;
    return 0;
}