nezachem 616 Practically a Posting Shark

This should really be posted in the assembly section.

I don't think so. There's enough problems with C in this code.

See comments inline.

I am stuck when i try to display the time on the Lcd panel. It can't seems to show any numbers and update itself. It will keep printing some wierd thing and eventually cover up the " Clock: " word. I am using keil uVsion 3 complier.

Here is my code, hope someone can give me some guidance as i am new and weak in programming. Thanks in advance!

void Lcd_Write(unsigned char Data);
unsigned int sec, min, hour;

void main (void)
 {

	Lcd_Command(0xc0);						 // print at 2nd line
	while(1)
	{
		Lcd_Write(hour);		   
// Lcd_Write is declared as Lcd_Write(unsigned char. hour is 
// declared as unsigned int.
		Lcd_Write(':');
		Lcd_Write(min);
		Lcd_Write(':');
		Lcd_Write(sec);
// Don't you need some command to get back to the 
// beginning of the 2nd line?			

}
nezachem 616 Practically a Posting Shark

this is the error i'm getting.
g++ main.cpp
g++ universityperson.cpp

When you invoke g++ with no options, it will try to make an executable. What you need is an object file.
In all your %.o rules (that is, everywhere except UniversityPerson) change g++ to g++ -c . A -c option stands for "compile only", that is produce an object file, to be linked later.

//makefile

UniversityPerson : main.o universityperson.o employee.o academic.o faculty.o   \
teacher.o administration.o support.o student.o
        g++ -o UniversityPerson main.o universityperson.o employee.o academic.o\
 faculty.o teacher.o administration.o support.o student.o

main.o : main.cpp universityperson.h
        g++ [B]-c[/B] main.cpp

universityperson.o : universityperson.cpp universityperson.h
        g++ [B]-c[/B] universityperson.cpp

employee.o : employee.cpp employee.h
        g++ [B]-c[/B] employee.cpp

academic.o : academic.cpp academic.h
        g++ [B]-c[/B] academic.cpp

faculty.o : faculty.cpp faculty.h
        g++ [B]-c[/B] faculty.cpp
teacher.o : teacher.cpp teacher.h
        g++ [B]-c[/B] teacher.cpp

administration.o : administration.cpp administration.h
        g++ [B]-c[/B] administration.cpp

support.o : support.cpp support.h
        g++ [B]-c[/B] support.cpp

student.o : student.cpp student.h
        g++ [B]-c[/B] student.cpp
nezachem 616 Practically a Posting Shark
srand(time(0));


int main()
{
    Walk(fAverageMoves, iTotalMoves, iTotalHome, fAverageHome, N, x,
    iTotalPub, fProbHome); 
    return 0;
}

You are trying to call functions outside of any function. Put srand(time(0)); inside main.

nezachem 616 Practically a Posting Shark

> How would I fill a two-dimensional array up with numbers
Exactly the way you do it.
> But when I try to print it out it comes up with wierd numbers I printed with:
If you give us more context, we might spot a problem.

nezachem 616 Practically a Posting Shark

> I can't explain the exact difference actually in writing to satisfy you.

The difference is right here:
> answer *= n; If you look closely at your first example you will see that there's no assignments, not a single one. An assignment changes what is technically called a state. The truly recursive solution doesn't have the notion of state. It doesn't use assignments even for the local variables. In fact, a properly implemented functional (that is, recursive) language has no concept of a variable whatsoever.

BTW, uskok didn't give any implementation details. Until I see the code I wouldn't say if it is a "true" recursion or a "false" one.

> Strictly speaking, this problem is not recursive in nature.

Strictly speaking, problems do not have nature. Everything solvable "procedurally" has a purely recursive solution (a Turing machine is computationally equivalent to a Church's lambda calculus to a Markov's recursion etc etc)

To illustrate a point, here is a purely recursive solution of a subproblem: find if an array contains a given number (it is intentionally written in haskel; I don't want to do somebody's homework):

if_has_value :: Int -> [Int] -> Bool
if_has_value v [] = False
if_has_value v (x:xs) | v == x = True
                      | _      = if_has_value v xs
nezachem 616 Practically a Posting Shark

I have MS word file containing text data

Then start here

nezachem 616 Practically a Posting Shark

The file contains binary

if((cfPtr = fopen("Error Pattern 2.dat","r") ) == NULL)
					fscanf(cfPtr,"%d", &Array[j]);

Binary file needs to be opened in binary mode ("rb"), and may not be read with fscanf(). Use fread() instead.

Beware the portability issues.

nezachem 616 Practically a Posting Shark

You did not use a debugger.

nezachem 616 Practically a Posting Shark

well from what i am trying to do is take a program from c++ and convert it to c, so should airline be a struct?

Yes.

this is what it looks like in c++

class airline
{       private:

        struct passenger
        {       int id;
                int res_num;
                string phone;
                int seat;
                char menu;
                string lname;
                string fname;
                passenger* next;
        };
        passenger *head, *cur, *pre, *nptr;

        public:
                airline();
                char menu();
                void make_reservation(int seat_counter);
                void print();
                bool search_pass(int key);
                void change_reservation();
                void reports();
                bool cancel_reservation(int key);

and that's approximately how it would look in C (don't forget to alter strings into char * and treat them appropriately):

typedef struct passenger
        {       int id;
                int res_num;
                string phone;
                int seat;
                char menu;
                string lname;
                string fname;
                struct passenger* next;
        } passenger;

typedef struct airline
{
        passenger *head, *cur, *pre, *nptr;
} airline;
 
airline *     airline_init();
char           menu(airline *);
void           make_reservation(airline * int seat_counter);
//etc
nezachem 616 Practically a Posting Shark

So, what is airline at line 48?

nezachem 616 Practically a Posting Shark

Can you elaborate on the need of
> direction = (randint(1,5)+randint(1,5)+randint(1,5)+randint(1,5))/4

Hint: this will give you neither better random, nor a uniform distribution.

nezachem 616 Practically a Posting Shark
MYDATE=`date +%d_%m_%y-%H-%M`
DIREC="/Volumes/Jobs-2008/Incoming_JOBS/"$MYDATE
mkdir $DIREC
cp $1 $DIREC "/" $2

Path and name are passed as the command line arguments, and the script accesses them as positional parameters 1 and 2. $1 and $2 in the code above are their respective values.

PS: Make sure there's no spaces around "/" at line 4.

nezachem 616 Practically a Posting Shark

My problem is in my void check_name() function... the function that checks if the name is in the list and then displays it as well. When the program runs for some reason it only works for the first set of names (the #1 boy and girl) but in an infinite loop.

void check_name()
{   name *strt;
    strt = start_ptr;
    cout << endl;
          
          for (name * strt = start_ptr;strt->nxt !=NULL;strt=strt->nxt)
          {      
                if (enter_name == strt->boy_name && enter_name != strt->girl_name) {}
                // etc
          }
}

In this code, the next search starts from the point where the previous search ended. You need to start each search from the very beginning of the list.

This mistake stems from the wrong design decision: the function that checks if the name is in the list and then displays it as well is a bad function. Split the functionality into "find the record" and "display the (found) record".

nezachem 616 Practically a Posting Shark

yes you are right.

but still i dont understand the second one.
printf("%s%s","hello""world");
how that is getting concatenated

as it getting garbages because there is no value for second %s.

You have two strings with nothing between them. The preprocessor combines them together. It is a documented language feature. "aaa" "bbb" is the same as "aaabbb" .

nezachem 616 Practically a Posting Shark

Hi, I'm reading a line from a text_file.txt

The line looks like:
1#Jonh#Smith#PO Box#4.9#5.0#

What did you see in Cli_nombre?

getline() will return a single line from your file.

Up to delimiter. He is calling getline(file, ..., '#');

nezachem 616 Practically a Posting Shark

Take a look at ImageMagic

nezachem 616 Practically a Posting Shark

They look like exercises on a topic of dynamic programming. This can be a good start.

nezachem 616 Practically a Posting Shark

There is a nice utility called 'man'. Type 'man wait' at a command prompt and read the documentation.

And yes, wait is the only way to inform parent that child terminated. Besides, omitting wait() will lead to some nasty surprises.

nezachem 616 Practically a Posting Shark

Do you call wait() in the parent process?

nezachem 616 Practically a Posting Shark

OK. One step at a time.

char *ptr = "String";
	char arr[]= "Array";
	*ptr ='T'; // behaviour is undefined

ptr points to a string literal, which resides in a read-only section of your data. An attempt to modify it results in segfault, GPF or something else depending of the platform (it may even succeed if a memory protection is not implemented)

arr, however, is allocated on a stack and is just initialized from the literal. This memory is perfectly writable.

arr = ptr; // not allowed

Arrays are not pointers. The are "same" only as function arguments.

printf("Hello" "World"); // HelloWorld

The preprocessor does concatenate strings, that is right.

printf("%s%s","Hello" "World"); // HelloWorld(someGarbage)

You pass one parameter (the concatenated string) and ask to print two.

nezachem 616 Practically a Posting Shark

> from the command line

Can you show the command line?

nezachem 616 Practically a Posting Shark

OK, now I get what you doing.
Let me reiterate: use a debugger. It is entertaining and enlightening. You will immediately see how do you actually print. Hint: lines 33 through 37 have only one chance to run.

nezachem 616 Practically a Posting Shark

Frankly, I did not get what you are trying to do, but maybe that's just me.

Hello,

The above code gives me values for only one text file and then goes in to an infinite loop. The other text files are generated though as empty files.

Once you completed an inner loop once, you have read everything from the file, that is reached the end of file, that is all subsequent reads do not produce any data. Either fopen and fclose your filename in each iteration, or rewind it (in each iteration, of course).

nezachem 616 Practically a Posting Shark

First of all, next time please use a code tag.
Second, in such situations it is highly recommended to use a debugger.
Third, let's see what happens if the very first answer is -1: size becomes 2, head->item becomes -1, head->next is not NULL.

How many iterations will the printing loop go through? Of course it will never see the final node.

My recommendations:
1. You do not need the if/else inside the loop (hint: you print "{" outside of the loop; why would you want to print "}" from inside?)
2. Do not use size for list traversals. The list has an inherent end marker.

nezachem 616 Practically a Posting Shark

Start with Core Audio API

nezachem 616 Practically a Posting Shark

Pay attention to lines 48 and 49.
At line 48 you print (i, j, k) as soon as they sum up to x, regardless of their relative primarity. Then at line 49 you test their primarity - and do nothing with the result.
You should print data only if the test at line 49 succeeds.

By the way, a loop at line 47, along with test at line 48 just waste processor cycles. The value of k is known right away. Do you see what I mean?

coolfriends commented: Thanks a lot +1
nezachem 616 Practically a Posting Shark

I have the following code which works on the .txt file
...
Can anyone please help me how can i avoid the memory leaks here

Frankly, I don't see how it may be freed at all. Judging from the code, you build a list of chunks, and besides that each chunk is referenced from keyword. The keywords themselves, as far as I can tell, are only accessible through the chunks. Is it what you have intended?
If so, don't call it memory leak. If not, describe your intended data structure design and we can figure something out.

nezachem 616 Practically a Posting Shark
new

Awww it was a C forum not C++
I shall be dragged in the slime and the mud.

jephthah commented: Christ I know you can't hear me / But I only did what you wanted me to / Christ I'd sell out the nation / For I have been saddled with the murder of you / I have been spattered with innocent blood / I shall be dragged through the slime and the mud. +5
nezachem 616 Practically a Posting Shark

I don't understand why every time, the list_insert method is entered and new linked_list node is created the address of the node is shown to be the same.

I need some help please.

Thanks.

A simple answer is that the node you created is destroyed each time you exit list_insert. It happens because node is local to list_insert, and exists only in the local scope. The local scope variables live on the stack. The stack has in important property: upon a function exit it looks exactly as it was at the function call time; anything local to a function is gone and forgotten. When you call the it again, its local variables are created as if nothing happened before, and since you call it in the same context, another node is (temporarily) allocated at the same place, and destroyed upon exit, and nothing is new under the sun.

To escape this sansara, learn the difference between

void list_insert(list* lst, int x)
{
	linked_list node;

and

void list_insert(list* lst, int x)
{
	linked_list * node = new linked_list();
nezachem 616 Practically a Posting Shark

There are three things in your code which require attention.
First, buttonstatus is lost as soon as VariableDialog.apply returns. To keep this value, simply return it:

def apply(self):
      buttonstatus = self.status.get()
      return buttonstatus

Then, to get the value you are interested in, call the apply method: status = [I]something[/I].apply() Final question - what is this something? It must be an instance of VariableDialog class (because it is where apply() is defined). Notice that you already created this instance at line 12 of MainScript. You just need to remember this created instance; then you may call its methods:

dialog = ChildScript.VariableDialog(master)
      # From right here, I would like to be able to print the value of 'buttonstatus'.
      status = dialog.apply()
nezachem 616 Practically a Posting Shark

Is comctl32.lib added to your project?

nezachem 616 Practically a Posting Shark

Heya folks. I'm trying to write a BMI calculator, but I'm missing something.

Splint tells me I have a parse error before the scanf, but I'm not seeing it.

#include <stdio.h>

int
main() 
{
	float height, weight;
		
	printf("Enter your height in inches and weight in pounds: \n");
	scanf("%f%f", &height, &weight);
 	float bmi = (weight/(height*height));	
	...

You have a variable (bmi) declared not at the top of a block.
This is valid only in a c99 domain; most likely splint assumes an older standard.

nezachem 616 Practically a Posting Shark

>>May I ask what lead you to this conclusion?

Yes, just think about it for a second.

  1. mystart is an integer pointer
  2. MyArray is an array of integers
  3. first is a pointer to a structure
  4. The compiler can not convert an array of integers into an array of structures. Well, it can by typecasting but the result will be just so much shit.

Strictly speaking, it is an array of uint_8, and given the lack of the context we may only guess what uint_8 really is, especially what its alignment requirements are.
Now, the only reason for shittiness (which I believe is a nice way to say UB) would be a structure (in this case a pointer, actually) having stricter alignment. As a side note, IA32 forgives even that.
Otherwise, the code is 100% valid C.

nezachem 616 Practically a Posting Shark

I'm fetching a list with all files/folders on a ftp-server,
I want to put a [F] before a folder, and leave files like they are,
but I can't find a way to check if it's a file or a dir...

I already tried:

from ftplib import FTP
import os
ftp = FTP(self.host)
listdir = self.ftp.nlst()
for i in listdir:
    if(self.ftp.sendcmd(os.path.isdir(bool(self.ftpdir + "/" + i)))):
          self.list_box_2.Append("[F] " + i)

But this ends in an error:

Of course.
You have to use ftp.dir instead of ftp.nlst, and massage the returned list (it will have the information you need and a lot more).

nezachem 616 Practically a Posting Shark

Hey everyone, so I am having a really annoying problem with my code.

The goal of it is to be able to read a text file of an unknown length (it's more or less a class roster w/ scores) and calculate and display the average of each student. The code compiles without errors but when run it has huge numbers as answers rather than an ID, name, and average.

Thanks for the help!

Text file

1000 John   9.5  9.0  8.5  8.0  8.5  87.0  92.5  86.0 
2000 Tom   10.0  6.7 10.0 10.0 10.0 100.0 100.0 100.0 
3000 Alice  6.9  8.0  8.0  8.0  8.0  80.0  80.0  80.0

Program

void input_scores(int id[], [B]char Name[][/B], double avg[], char letter[], int size, char input_file[]){
...
	in_file >> Name[i];

Notice how Name is declared - it's an array of chars. That is, Name is a char. It means that you are reading not a name, but a single character. That means in turn that all subsequent reads are wrong.

BTW, a debugger helps immensely.

nezachem 616 Practically a Posting Shark

Hello,

If I run the mkdir part by itself it works fine. I just cant seem to get the file to copy into this newly created directory.

This is what I have tried:
(The words in brackets are the tokens for dir path and filename.)

mkdir /Volumes/Jobs-2008/Incoming_JOBS/`date +%Y-%m-%d-%H-%M`
cp <FILE> /Volumes/Jobs-2008/Incoming_JOBS/`date +%Y-%m-%d`/<FILENAME>

Any pointers would be appreciated
thanks.

First of all, the names of a newly created directory and the copy target directory are different (the former does have hours ind minutes, and the latter does not).
Next, you should not invoke 'date' twice - there's always a risk that the second invocation returns different result.
Therefore:

DATE=`date ... ... ...`
PATH="/Volumes/.../.../.../"${DATE}
mkdir ${PATH}
cp <FILE> ${PATH}/<FILENAME>
nezachem 616 Practically a Posting Shark

That code compiles but I get a wicked error that I have never seen before. What's wrong with this?

dp = opendir (".");
  if (dp != NULL) {
      while (ep = readdir (dp)){
...
      closedir (dp);
      }
  }

Do you see anything funny about this fragment?

nezachem 616 Practically a Posting Shark

I can print all the files and directories like this

#include <stddef.h>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

int
main (void) {
  
  DIR *dp;
  struct dirent *ep;

  dp = opendir (".");
  if (dp != NULL) {
      while (ep = readdir (dp))
        printf("%s\n", ep->d_name);
      closedir (dp);
  }
  else
    perror ("Couldn't open the directory");

  return 0;
}

But how do I do this?

If (file is a sub directory)
open it, and print those files.

First of all, you need to be able to tell files from directories. I am not sure if a dirent has such information; in any case you may stat the name:

struct stat statbuf;
stat(ep->d_name, &statbuf);
if(S_ISDIR(statbuf.st_mode)) {
    // It is a directory
}

Second should be obvious: once you detect a directory, recurse into it.

nezachem 616 Practically a Posting Shark

You must realize that in C strings are not first class citizens. There's no support for them in the language. There's no operator to compare them. There's strictly speaking no such thing as a string.
What is there is a memory region occupied by bytes, and a pointer to that region. You may think of it as an address of the region.

The comparison operator '==' compares just those addresses.

Now notice that in your program there are two distinct memory regions: one called "name", and another one, where lives the string literal "Amanda". They are distinctly different; they appear at the different addresses. Of course the comparison fails.

What you really want to do is to test that those regions contain the same data. For that, you need to compare them byte by byte. You may do it manually (I bet you know what the for loop is), or call a library function such as strcmp, which exists specifically for that purpose.

nezachem 616 Practically a Posting Shark

Use chdir. stat also works, although it may lead to race condition.

nezachem 616 Practically a Posting Shark

thanks for your help but i guess i am not understanding it clearly..
i would really appreciate if you could show me in code...

thanks

Something along the lines of

int k = 1;
int i = N/2 + 1;
int j = N/2 + 1;
while (k < N) {
    int s;
    // going right:
    for (s = 0; s < k; s++, i++, I++)
        arr[i][j] = isPrime(I)? I: -1;
    // going up:
    for (s = 0; s < k; s++, j--, I++)
        arr[i][j] = isPrime(I)? I: -1;
    k++;
    // going left:
    for (s = 0; s < k; s++, i--, I++)
        arr[i][j] = isPrime(I)? I: -1;
    // going down:
    for (s = 0; s < k; s++, j++, I++)
        arr[i][j] = isPrime(I)? I: -1;
    k++;
}
nezachem 616 Practically a Posting Shark

Thanks Nezachem! I have changed quite a lot in the code, and now it does work, with a few exceptions unhandled (like segfaults when getting a permission denied), but those were not mentioned in the assignment anyway.

My main problem was with line 6, where I changed char *com[] to char* com[50], and that started working. I still have no idea why, this being far from my area of expertise, but the girl says she knows why, and that's good enough for me :)

strtok() was a requirement for this assignment, as well as execv(), can't do much about it.

I'm going to dwel on the man pages for wait() now, posting the current working version, in case you have the time to have a look and suggest improvements

I am glad I helped. Few comments:
1.

tempcmd=cmd; //assign to temp variable, so strtok doesn't ruin cmd

doesn't do what the comment claims. The actual string containing cmd remains the same - it just gets accessed via another pointer - and strtok happily ruins it. What you need to achieve the stated goal is to

strncpy(tmp, cmd, sizeof(cmd));

2. Your path-finding logics seems broken. The code sequentially tries to run the command from each path component. Obviously, most of the times the command is not there, resulting in a "No such file or directory" error. Through my crystal ball I can see that your test at line 72 does not catch it. This is because in C …

kvprajapati commented: Great! +6
nezachem 616 Practically a Posting Shark

The main loop should fill the array (not print it, but just fill) in the following manner:

K steps to the right
    K steps up
    increment K
    K steps left
    K steps down
    increment K

Break the loop as soon as K reaches N.
Of course, each step increments I as well.
A step to the left changes current coordinates (i, j) to (i - 1, j), a step down - to (i, j + 1) etc.
Once the array is filled up, print it in another loop.

nezachem 616 Practically a Posting Shark

Thanks, but the article uses execve, which is not an option for me in this case.

I was just looking for an explanation for line 46, 52 and 54 in my code

First of all, what difference does this little 'e' make?

Second, it is not a C question, but rather Unix one. To help your GF you need first to understand the unix process model.

Third, thou shall not strtok.

Now, for your questions.
Line 46: a function from the exec family does not return if succeeds. If it does return it means it failed. This is what a printf is supposed to inform the user about. Keep in mind that the way the code is written, a status is garbage.
Line 52: a wait function waits for a child process to finish (not quite, but for the purpose of this assignment it is OK to assume so). Here the status tells how did it finish, and the code needs to analyze its value, which it half-heartedly attempts to do at line 54. Do 'man 2 wait' for the WIF* macros.

I hope I am not too late with this. There are many problems with this code I didn't even mention.

nezachem 616 Practically a Posting Shark

Where did you get that crappy code from??? Toss it out and forget it.

With all due respect, you are wrong. The code is quite ugly yet perfectly valid.

>> myend = &MyArray[MAX_SIZE];
Wrong -- myend is set to point one element beyond the end of the array, a common mistake. should be myend = &MyArray[MAX_SIZE=1];

It is OK to point an element one beyond the end. In most platforms it is OK to point anywhere, but the Standard specifically allows pointing off by one. Of course, you shall not dereference such a pointer, and the code does no do that (see line 16 of the last listing).

>>first = (MyLL *) mystart;
Illegal operation. mystart can not be converted to MyLL structure.

May I ask what lead you to this conclusion?

Good morning coders !,
Why is that array so useful? Is it a sort of method to save up space for consecutive linked list pointers ?

I could really sue your help because the moment I thought linked lists were clear , this is shaking my confidence...

Thanks in advance,

T

With just an initialization code, one may only guess how it is used. Please inspect what else (and in what circumstances) happens with the list and the array in general; if you still have questions, the details are appreciated.
My guess would be it is a poor man's malloc in a malloc-less environment. Each MyLL (appearing in the array …