Salem 5,265 Posting Sage

Read this first - http://www.daniweb.com/techtalkforums/announcement8-2.html

> student from engg college
So start studying then.
Your qualification will be meaningless if all you do is google all your answers or try and get other people to do the work for you.

When you do get around to posting your own work, don't forget this
http://www.daniweb.com/techtalkforums/announcement8-3.html

Salem 5,265 Posting Sage

Well if you've already created functions to read a whole record and write a whole record, then perhaps something like

int matchID ( record *rec, char *ID ) {
  return strcmp( rec->ID, ID );
}

Based on the result, you can decide whether (or not) to output the record to the screen, another file or whatever.

Salem 5,265 Posting Sage

This has some good information as well
http://www.nondot.org/sabre/os/articles

Salem 5,265 Posting Sage
Salem 5,265 Posting Sage

> I am being returned incorrect values for circum and area variables.
You got the calculations the wrong way round
area is pi*r*r
circumference is pi*2*r

> return x,y;
This does NOT return two values, it returns y

Also, you're using a class containing data, there is no need to keep passing results back and forward in parameters.
Your data should also be in the private section of the class.

The member class member functions have automatic access to class member data.
So you should be able to do this

switch(display)
 {
  case 1: myCircle.printRadius();
   break;
  case 2: myCircle.calculateArea();
   myCircle.printArea();
   break;
  case 3: myCircle.calculateCircumference();
   myCircle.printCircumference();
   break;
Salem 5,265 Posting Sage

> If no, then why calloc() is returning NULL to the array
Well your use of 'far' strongly suggests the fact that you're using an ancient 16-bit compiler rather than a more modern 32-bit compiler.

The maximum single allocation you can have is 64K (your array is 128K).

@ andor
> array = calloc(256, sizeof(int)); This is wrong - it assumes int's and pointers are the same size. It should be array = calloc(256, sizeof(int*)); To save confusion (and even thinking about it), p = calloc ( 256, sizeof *p ); will always be correct, no matter what the type of p is.

~s.o.s~ commented: good one, hats off to you sir[~s.o.s~] +2
Salem 5,265 Posting Sage

> void fun(int **array)
The rule about arrays become pointers is not recursive - it only happens for the outermost level of the array. void fun ( int (*array)[40] ); is one way to declare the function.

This is another way, which is easier to remember since it's just copy/paste of the original array that you want to pass in the first place. void fun ( int array[40][40] ); Either form is equivalent, and you can of course use [row][col] indexing on the array inside the function just as you would outside the function.


Yes, main does return an int by the way.

Salem 5,265 Posting Sage

So where is the linked list, or anything else you spoke of 2 weeks ago?

Salem 5,265 Posting Sage

You've basically written this

struct node {
  int a;
  struct node {
    int a;
      struct node {
        int a;
        struct node {
          int a;
          struct node {
              int a;
              struct node x;  // and so on....
              struct node *pnext;
          }x;
          struct node *pnext;
        }x;
        struct node *pnext;
      }x;
    struct node *pnext;
  }x;
  struct node *pnext;
};

You can't infinitely expand copies of yourself when declaring a structure.

The way the cycle is broken is by having a pointer, which is always a fixed size regardless of the amount of data being pointed at.

Grunt commented: Nicely Explained - [Grunt] +1
andor commented: nice explanation (andor) +2
Salem 5,265 Posting Sage

So how much have you managed yourself?
- reading a line in
- separating the number and the word
- storing them in an array
?

Post what you can achieve, then the answer will be more likely tuned to your specific needs.

It also shows you've done some work and not just dumped your assignment on a message board.

Salem 5,265 Posting Sage

Providing the author did the job properly, all you need to do is recompile it on the target machine.

Salem 5,265 Posting Sage

> HWND hTemp = FindWindow("tibiaclient", NULL);
The newer compilers use UNICODE by default.

I think you can either turn this off.

Or prepare your code for the future by writing
HWND hTemp = FindWindow( _TEXT("tibiaclient"), NULL);

http://www.i18nguy.com/unicode/c-unicode.html

Salem 5,265 Posting Sage

http://en.wikipedia.org/wiki/Big_O_notation

> why we ignore constant for example f=100n
Because it's meaningless when you're considering the "asymtotic" behaviour. Like 100*infinity is no different to 50*infinity or just infinity.

Such minor order terms only come into play for small n, and vary widely depending on such things as
- the processor
- the compiler
- the language
- the skill of the programmer
- the actual size of n
- the actual data being manipulated
- etc etc.

Salem 5,265 Posting Sage

> cin >> degrees;
You need to add to a running total of temperatures, then divide that total by 10 to get the average.

Salem 5,265 Posting Sage

> for (int i = 0; i <= 12; i++)
> for (int j = 0; j <= 11; j++)
> for (int k = 0; k < 11; k++)
Only one of those loops correctly accesses all the elements of your array.

One of them steps off the end, no doubt trashing something else into the bargain.

for ( i = 0 ; i < N ; i++ )
No need for <=
No need to subtract one from the size of the array.

Salem 5,265 Posting Sage

In an equally pointless vein

// a = a + b
while ( b-- ) a++;

OK, so there are some side effects, and a bug or two ;)

> I wanted to know the C Statement for adding two numbers without using + sign..
Study what exclusive-or and bitwise-and give you for a single pair of bits.
Hint: exclusive-or adds two bits without carry.
That's all I'm saying without giving the whole game away, and that's probably too much anyway.

Grunt commented: Nice-[Grunt] +1
Salem 5,265 Posting Sage

Read this, then edit your code to make it presentable
http://www.daniweb.com/techtalkforums/announcement8-3.html

You didn't actually ask a question, nor make any suggestion as to what you think is wrong with the code (or the symptoms you get when you do run the code).

Just dumping the code on a message board, especially a lot of code isn't going to win you many friends.

Salem 5,265 Posting Sage

> and I believe that text fields which contain commas should be enclosed in quotes.
Yeah, I wasn't going there - too tricky ;)
If the strings contain quotes as well as commas, its going to get ugly.

Salem 5,265 Posting Sage

> is because windows functions only accept char*,
So how do you know that those functions are not going to modify the string?

Now some windows functions are sloppy in the use of const, but then again perhaps they're not const for a reason. Since you're being vague about what it is you're trying to do, we'll just have to guess.

The only safe way out is something like

char *foo = new char[ str.length() + 1 ];
strcpy( foo, str.c_str() );  // make a copy you know you can change
someAPICall ( foo );  // some function which doesn't like const
delete [] foo;

> No it works, i tried it.
Today, maybe, with your current compiler and particular program.
Long term, in the future, you're gonna get bitten really hard when you least expect it (mostly near a deadline).

Programming is a habit of doing the right thing when it doesn't matter so you'll do the right thing when it does matter. The attitude of "works for me" won't wash long term.

Sometimes, people really do have to fall off a cliff just to figure out gravity exists. Enjoy your future flight.

Salem 5,265 Posting Sage

> I get a lot of error related to iostream.h file not being found
iostream.h is old C++.

The new way is

#include <iostream>
using namespace std;
int main ( ) { 
    cout << "hello world";
}

Or

#include <iostream>
int main ( ) { 
    std::cout << "hello world";
}
Salem 5,265 Posting Sage

> ohh i forgot im trying to use link list
Your point being?

It's all the same logic no matter what data structure you have.

Are you storing the most significant digit at the head of the list, or the least significant digit?

Salem 5,265 Posting Sage

As in

char n1[] = "358";
char n2[] = "235";
int carry = 0;

sum = carry + (n1[2] - '0') + (n2[2] - '0' );  // Add "8" and "5", as 8 and 5
result = sum % 10;  // ie 3
carry = result / 10;  // ie 1

// Then you do the same for n1[1] and n2[1]

Essentially, you model the algorithm on how you would do the sum on paper. Start at the right hand end of the number and work to the left.

It's easy when the numbers are the same length, you just need a little more care to line up the numbers when you have say

char n1[] = "123456";
char n2[] = "78";
Salem 5,265 Posting Sage

> is an assignment like fn4[23] = fn3[5] invalid?
Well it's fine as far as the syntax is concerned.

However, the pointer inside the structure presents big problems.

fn1.y = malloc( 10 * sizeof *fn1.y );
fn2 = fn1;
free( fn1.y );
// fn2.y is now a dangling pointer.

Structure assignments in C know nothing about the internals of the struct, it's just a handy wrapper around memmove( &fn2, &fn1, sizeof fn2 ); In C++, we would use a proper copy constructor to replicate what the pointer pointed to rather than just making a copy of the pointer.

Dave Sinkula commented: --Dave +7
Salem 5,265 Posting Sage

Like 3 = myVariable; Will generate an lvalue error, because you can't assign to a numeric constant.

You can't assign to a function, or assign to an array either.

Grunt commented: Helps +1
Salem 5,265 Posting Sage

> int **EL= (int**)malloc(row*col*sizeof(int) + col*sizeof(int*));
1. You didn't include stdlib.h
2. Since this seems to be C++, you should be using new anyway.
3. Since your sizes seem to be constant, why are you dynamically allocating anyway?

I see that lot adds up to at least a couple of MB, so that probably explains why you gave up on int EL[row][col]; There are several ways out, which don't involve a lot of mess.

1. Make them static, you get the scope without the stack space static int EL[row][col]; 2. Dynamically allocate in one go, since the minor size is constant. int (*EL)[col] = new int[row][col]; Note the placement of the ( ), very important you get these right.

3. Since this is C++, use a vector vector< vector<int> > EL;

Salem 5,265 Posting Sage

What happens if the same word appears on a single line more than once?

You could try map<string,vector<int> > to associate a word with a list of line numbers.

Salem 5,265 Posting Sage

> #define Mess1 "\n\rWaterflow Sensor";
Well the ; at the end of this line should really have drawn a syntax error from your compiler, not a pointer convertion error.

Which leads me to suspect you've posted from memory what you think you've got, rather than copy/pasting what you've actually got.

A complete compilable example program which demonstrates the problem is far better than 3 disjointed lines which contain other problems.

> i have the following defined on top of the program in C
You might be writing in C, but does your compiler know that?
Too many people name their C programs with filenames like prog.cpp and get into all sorts of trouble as a result.

Saying which OS/Compiler you're using as well would help, since the functions you're calling are non-standard.

Did you prototype the function before calling it?
Is the prototype consistent with the definition?

Salem 5,265 Posting Sage

1. Your class it at least missing it's closing ;

2. By failing to use code tags, certain class member functions have been replaced by smilies.

3. Why on earth are you still using char* to store strings. This is C++, and you already include <string>, so why not just use it for every string?

Likewise using <vector> to store all the cards rather than rolling your own array is probably safer as well.

4. PlayerName_[strlen(PlayerName)] = '\0';
This is a waste of time - arr[strlen(arr)] is always \0, so in the end nothings changed.

Salem 5,265 Posting Sage

> #include "stdafx.h"
Delete this from the project and disable "Use precompiled headers" in the microsoft compiler.

> #include <malloc.h>
This is an obsolete file, you don't need this. malloc etc are declared in stdlib.h

You're also missing stdio.h and string.h

> (69) : error C2664: 'FindFirstFileW' : cannot convert parameter 1 from 'char [260]' to 'LPCWSTR'
You need to disable the UNICODE option, or make use of the TEXT() macro around all string constants in your program.

About 99% of this program is actually C (not C++)
Are you sure about your choice of language?

Meh - beaten

WolfPack commented: Thanks. I missed some errors. +3
Salem 5,265 Posting Sage

> where error?
Please use the code tags when posting code - can't you read this
http://www.daniweb.com/techtalkforums/announcement8-3.html
Or see the background image in the compose message window?

Also, count the { and }
I count 3 { and only 2 }

Salem 5,265 Posting Sage

> How to swap two variables without using a third variable & pointer?
This ceased to be interesting when we came down from the trees and started using high level programming languages.

If your "teacher" somehow thinks this is a good idea you need a better teacher.

http://en.wikipedia.org/wiki/Xor_swap
Way too many special cases for it to be considered anything more than a party trick.

Another recent post on the same subject.
http://www.daniweb.com/techtalkforums/thread49488.html

Salem 5,265 Posting Sage

> char *bin;
Listen to the people - you need to allocate some memory.
You can't just declare a pointer and assume you have an infintely long string you can play with at will.
This is just some random location in memory.

Start with char bin[100] = { 0 };

Salem 5,265 Posting Sage

> from INDUSTRIAL POINT OF VIEW.. with Problem Description
You have two lifts in a office building and 5 floors to service.

Design a control system which responds to the button presses on each floor and button presses within each lift to achieve optimum performance (least delay for each user).

Enhance this by recording usage statistics to enable the lifts to wait on the most appropriate floors at appropriate times of the day.
For example, at the beginning of the day, most people arrive and therefore waiting nearer the ground floor is a good idea.

WolfPack commented: good suggestion +3
Salem 5,265 Posting Sage

Well you could help yourself by telling us which actual error messages you see.

> am compiling it in turboc
Ah, good old stone age technology - have you sharpened the stone chisel recently?

I'm also guessing you don't know the answer to the question "are you compiling C or C++" either. Sure it looks mostly like C, but that really depends on whether you called your file prog.c or prog.cpp.
Or whether you've passed any other options to the compiler to tell it which language to assume.

> for(int status =
C only got this kind of declaration in the C99 standard, which your compiler predates by decades, so it isn't going to support it.
I don't recall when C++ allowed this either, but I'd guess your fossil compiler won't even understand this in C++ mode either.

Declare the int at the start of the block (like you do for all your other variables) and see how you get on with that.

Now get a decent compiler (one made for this millenium) and leave turbo-c to the archaeology students.
http://www.compilers.net/Dir/Free/Compilers/CCpp.htm
Borland 5.5, Dev-C++, Digital Mars, MinGW, Microsoft Visual C++ express would all be a big step forward.

Late, but nevermind....

Salem 5,265 Posting Sage

> send me a program to remove unnecesary space from a string in turbo c++
Who gets to decide what is "unnecesary" ?

Read this
http://www.daniweb.com/techtalkforums/announcement8-2.html
Then make an effort.

Salem 5,265 Posting Sage
NAME
       ftw, nftw - file tree walk

SYNOPSIS
       #include <ftw.h>

       int  ftw(const  char  *dir,  int (*fn)(const char *file, const struct stat *sb, int
       flag), int nopenfd);
Salem 5,265 Posting Sage

> ya thaxs it works
Rather too easy to break IMO

#include <stdio.h>

int swap ( int *a, int *b ) {
  *a ^= *b;
  *b ^= *a;
  *a ^= *b;
}
int main(void)
{
  int a = 2, b = 3;
  printf( "%d %d\n", a, b );
  swap( &a, &b );
  printf( "%d %d\n", a, b );
  swap( &a, &a ); /* swap with itself */
  printf( "%d %d\n", a, b );
  return 0;
}

What do you get with the final line of output?
Is it what you expected?

Salem 5,265 Posting Sage

I don't know why you edited the file when the #ifdef was there just to make it so you didn't need to edit it :shrug:

Anyway, I'm now seeing the same problem on cygwin as well - which I suppose is progress in itself.

Here's my modified code - it's the same with a bit of extra debug on the end

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

int main(void)
{
  double x0,x1,a;
  int i;

  x1 = 1;
  x0  = 0;
  printf("Find square root of: ");
  fflush(stdout);
  scanf("%lf",&a);
  for(i = 0; i < 100 && x0 != x1; ++i)
  {
    x0 = x1;
    x1 = .5 * (x1 + a / x1);
#ifdef INCLUDE_PRINTF
    printf("Iteration %d - converging to %f - prev value %f\n",i,x1,x0);
#endif
  }

  printf("Finished in %d iterations\n",i);
  printf("Results: %.15f, %.15f\n",x0,x1);
  {
    union { double a; unsigned long b[2]; } v;
    v.a = x0;
    printf( "X0 in binary = %lu %lu\n", v.b[0], v.b[1] );
    v.a = x1;
    printf( "X1 in binary = %lu %lu\n", v.b[0], v.b[1] );
  }
  return 0;
}

Here are my results - the last two are the more interesting ones

$ gcc -W -Wall -ansi -pedantic -O2 -DINCLUDE_PRINTF foo.c
$ ./a.exe
Find square root of: 5
Iteration 0 - converging to 3.000000 - prev value 1.000000
Iteration 1 - converging to 2.333333 - prev value 3.000000
Iteration 2 - converging to 2.238095 - prev value 2.333333
Iteration 3 - converging to 2.236069 - prev value 2.238095
Iteration 4 - converging to 2.236068 - prev value …
Asif_NSU commented: That was really helpfull - Asif_NSU +3
Salem 5,265 Posting Sage

> I know about the issues involving comparison of double datatypes
"This is a hole, and I know I'm lying at the bottom of it."
What exactly were you expecting to happen?
If you know about the issues, why didn't you code around them and test on each compiler?

> The problem is if compiled with compilers other than gcc (I have tested it with lcc, visual C++ and borland C++
Proving that your code has undefined behaviour.

> but in this particular case it is guaranteed that x1 will stop changing after certain iterations.
Just because the printf outputs "1.234" and "1.234" does not mean the equivalent numeric test for inequality will fail. Printing things to only 6 digits of precision when doubles have 15 digits of precision is going to entail a certain amount of rounding.

> Uncomment the printf statement within the loop. And you will see everything works fine.
Try printing out the value of i at the end of the loop.
Without printf slowing it down, it's probably executing many 1000's more iterations. Which might mean it eventually stumbles upon convergence.

Adding a final "\n" to your printf would be a good idea as well.

Salem 5,265 Posting Sage

Read beej very carefully
http://beej.us/guide/bgnet/output/htmlsingle/bgnet.html
It has an example of how to use select.

Some points to note
> send(m_socket, strSend.c_str(), sz, 0);
Both send() and recv() can fragment the message. There is no guarantee that if you ask to send 20 bytes that it will happen in a single call. Even if the send() is a single call, the recv() can still be fragmented.
Making the whole thing non-blocking just makes this much more likely.

> So you think giving my program a 1 ms delay will correct this issue indefinitely?
Not at all.
Some points to ponder.
1. The sleep duration is a MINIMUM value only, so sleeping for 1 second and returning an hour later would be in spec.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/sleep.asp
"Suspends the execution of the current thread for at least the specified interval."

2. The OS time base is usually 10 or 20mS. Very short sleep periods get rounded up to the base OS scheduling interval.
http://www.geisswerks.com/ryan/FAQS/timing.html
Next OS upgrade, you could be looking for a different answer.

3. The actual amount you sleep will vary according to system load at the time. I mean, if your timer becomes very finely balanced, then all sorts of wierdness could result like
- my program runs fine during the day and crashes in the evening (sensitive to network load)
- my program is OK in debug, but crashes …

Dave Sinkula commented: I always forget about rep on this site. +4
Salem 5,265 Posting Sage

> for(int i=2; i<=((int)sqrt((double)n)); i++)
And it would be so much quicker if you didn't call sqrt() on every iteration of the loop!
n is constant (in this function), so it's root is constant also. Calculate it once and store in another variable to compare against.

Also, since 2 is prime, that's an easy case to get rid of, and you can start at 3.

Also, if you start at 3, then you can do i+=2 to only check all the odd numbers from there on.

hollystyles commented: good feedback +2
Salem 5,265 Posting Sage

> The problem I'm having is that when I use the function strstr() in a while loop, the console hangs
Well you don't advance the pointer, so it always begins the search from the same point, always finds the same match, and so on on on on .....

while ( (p=strstr(p,"thing")) != NULL ) {
  // do something

  // start search from just past the previous hit
  p++;
}

> gets(array);
NEVER use gets() to read input, there is no way to make it safe.
Always use fgets().

> char string;
This should really be a local variable in some function.
Whether it's in main, and passed as a parameter to your function, or as a local within your function is up to you.

> while (*ptr != '\0')
This loop doesn't seem to append the \0 to the string you create.

Salem 5,265 Posting Sage

> void displayCalendar(unsigned month, unsigned year, int* daysOfMonth[])
The simplest rule is to simply copy/paste the declaration of the array you want to pass, so it would be void displayCalendar(unsigned month, unsigned year, int daysOfMonth[]) Calling the function, you just use the array name, so instead of displayCalendar(month, year, daysOfMonth[]); It would be displayCalendar(month, year, daysOfMonth);

Salem 5,265 Posting Sage

> int sr = recv(acc, buffer, sizeof(buffer), 0);
1. recv doesn't store a \0 on the end to make it a proper string
2. You need to leave room to store the \0 yourself
3. You need to code for the possibility that recv() doesn't receive the whole message in one go (if this is a TCP connection)

int sr = recv(acc, buffer, sizeof(buffer)-1, 0);
if ( sr > 0 ) {
  buffer[sr] = '\0';  /* make it a string */
  /* now you can do str... operations on buff */
}
SpS commented: Agree:sunny +1
Salem 5,265 Posting Sage

> if ( filename == "day_01.txt")
Use if ( strcmp( filename, "day_01.txt" ) == 0 )

Rashakil Fol commented: Hello Salem! +1