Trentacle 112 Junior Poster in Training

Incorrect, and if you had read this thread more carefully you'd see at least two replies (one from mike_2000_17 describing the process and one from Schol-R-LEA with sample code) showing an easy way of doing what you say isn't possible.

I saw the replies, and I stand by my former statement.

Trentacle 112 Junior Poster in Training

so if i use stack as singly linked list i dont travel reverse when i pop it ?

You traverse the list, pushing each item (or a pointer to it) onto the stack as you reach it, then pop each item off the stack. You've added a new data structure (the stack), to which you copy the information in your linked list and read it out backwards. Conceptually this is the same as creating a new, reversed list.

I didn't say there is no way to reverse a singly linked list -- there obviously is. But there is no way to traverse a singly linked list backwards.

Trentacle 112 Junior Poster in Training

Ancient Dragon is correct, but I'd like to point out that there is a difference between

char *str = "Test";
/* and */
char str[] = "Test";

In both cases, "Test" is a string that resides in read-only memory. In the first case, str is a pointer object that is initialized to the address of the read-only string, as Ancient Dragon described.

But in the second case, str is an array object, and the initialization actually copies the string from read-only memory into the new (read-write) array. This memory has automatic storage duration, so it disappears when str goes out of scope -- you don't have to worry about free()ing it like you do with malloc().

As an aside, this kind of automatic copying is possible only with initialization, not ordinary assignment, so the following is not valid:

char str[100];
str = "Test";

This is because an array name is not an lvalue. The other version,

char *str;
str = "Test";

is more or less fine, but you must be very careful if you ever modify the string because str points to read-only memory. If you don't try to modify the string, declare it as char const *str; instead.

Ancient Dragon commented: good points :) +0
mike_2000_17 commented: Good points indeed! +13
Trentacle 112 Junior Poster in Training

there is no problem to do backward or frontward in single linked, as long as it is only one way to go needed, is more needed is both or one ? or you just go from start agayn to that spot you need. Or depends how much back you whant to go if it is by one to delete then you delete element-next not element and you good to go

I feel you're sincerely trying to help, but your post does not make sense. I imagine English is not your native language, so I have avoided being unnecessarily critical -- but as a native speaker, I have trouble following your train of thought every time I read one of your posts.

For starters, try to use complete sentences, and use more specific words than "do" and "go" -- I think you're probably talking about traversing the list (i.e., examining each element in order), but then it doesn't make sense to say that it's not a problem to traverse it backwards -- because there is, in fact, no way to traverse a singly linked list in reverse. If there were, it would be doubly linked.

Trentacle 112 Junior Poster in Training

I agree with pyTony, recursion seems like an odd way to solve this problem. However, you should be able to get your original version to work if you give it an array that can be modified (untested):

int main(void) {
    char *charset="abcdefghij";
    char buffer[100] = "";
    recurse(buffer,charset);
}

When you call recurse("", charset) the "" is a 1-byte character array in (probably) read-only memory. You can't strcat to it or modify it in any way without invoking undefined behavior.

I heard that if i use a function like with a global variable charset having A,B,C,D,etc.

\<code snipped>

You heard wrong then. strcat() modifies its first argument permanently. (This is not the case in e.g. Java, where strings are immutable and concatenation returns a newly created string.) strcat(3)

Trentacle 112 Junior Poster in Training

My last post was uncharacteristically harsh. Sorry about that.

I don't have a good opinion of VB -- I feel that it's popular in spite of its design, not because of it. It suffers from an unfortunate family tree, and on top of that, it's not an open standard (big black mark in my book).

Granted, it doesn't really compete in the same areas with any of the languages I regularly use, so I don't have anything to say about its use in any particular application. I just wouldn't advise it as a general purpose language for beginners.

Trentacle 112 Junior Poster in Training

I agree with you, but I didn't said that you need to cast a void pointer, I just said that it increases portability and robustness.

And I literally just explained why, in C, that is not true.

malloc() is not used in embedded systems (especially critical-safety systems such as the ones that are in automotive) because it leads to memory fragmentation and the allocation process can become quite slow if the memory is getting filled.

I was pointing out the fallacy of trying to apply MISRA to code that uses malloc(). It's like calling the cops because someone stole your marijuana.

Trentacle 112 Junior Poster in Training

I may be mistaken but I believe you have to by [sic] QT

If the rest of your post is also 12 years out of date, I'm not sure why I bothered reading it.

Few would be developing VB.net apps with GUIs without using an environment that removes the grunt work of placing visual elements, or an interactive debugger that supports breakpoints and step-by-step source level debugging.

I fail to see how fewer people using VB is a bad thing.

Trentacle 112 Junior Poster in Training

I'd also like to note that MISRA C forbids the use of malloc() altogether. Perhaps for related reasons.

Trentacle 112 Junior Poster in Training

There some C standards (such as MISRA) which recommend casting void*. Also, to my knowledge, this increases the portability of your code.

There are several legitimate reasons to cast a pointer-to-void, mostly to do with alignment. malloc(), however, is guaranteed to return a pointer of correct alignment for any type, so no alignment adjustment is necessary. Furthermore, in an assignment statement, the C standard requires that type conversion take place as if the RHS were cast to the type of the LHS. Casting the return value of malloc() is not just an extra step -- it's a complete no-op. Literally the only reason to do so is to suppress compiler warnings. Show me an implementation where omitting the cast affects the behavior and I'll show you a language that isn't C.

Trentacle 112 Junior Poster in Training

Quite so. Thanks for catching my mistake.

Trentacle 112 Junior Poster in Training

I'm going to guess you meant to post something more like this:

#include <stdio.h>
int main(int argc, char *argv[])
{
    if (argc != 2) {
        printf("usage: %s filename", argv[0]);
    } else {
        FILE *file = fopen(argv[1], "r");
        if (file == 0) {
            printf("Could not open file\n");
        } else {
            int x;
            while ((x = fgetc(file)) != EOF) {
                printf("%c", x);
            }
            fclose(file);
        }
    }
}

Now, did you have a question? Here are some good questions you might consider asking:

  • "When I run this with the wrong number of arguments, it terminates immediately and the usage message doesn't display! What am I doing wrong?"
  • "This program runs too slowly when I use it on large files. Can you suggest ways to speed it up?"
  • "I tried to use this program in a shell script, but I can't tell from testing $? whether it succeeded or not. How do I make my program return a meaningful value?"
Trentacle 112 Junior Poster in Training

Which is why you should instead use

array = malloc(ROWS * sizeof *array);

Also don't cast the result of malloc(), it suppresses warnings and serves no useful purpose. deceptikon's solution was in every way superior.

Trentacle 112 Junior Poster in Training

use g++ on linux if those ide are too hard to understand with g++ you will have full control

g++ is not a C compiler. Please make a token effort.

Sokurenko commented: Thank you very much!! +0
Trentacle 112 Junior Poster in Training

When you declare an array (or any object) within a function, the memory allocated for it has automatic storage duration, meaning that once the name it was declared with goes out of scope, trying to access the memory (via e.g. a persistent pointer, like you have done) results in undefined behavior.

There are three ways to pass arrays around among functions without running into trouble.

  1. Declare the array in the calling code and pass a pointer to it to the called function, which merely manipulates its content as opposed to returning something with the return statement. This is probably the most popular method and is how standard library functions like fgets() work.
  2. Within the function, use malloc() to reserve space for the array in dynamic memory and return a pointer to the allocated memory. This has the disadvantage that you have to remember to free() the memory when you're done with it.
  3. Wrap the array in a struct. Arrays within structs are passed on the stack just like other kinds of objects (i.e., the array doesn't "decay" into a pointer to its first element). This has several disadvantages, notably that it's unnecessarily complicated for simply passing an array, and doesn't work for arrays of unknown size at compile time (except with C99's flexible array members).

So, yeah, pretty much those are your options.

Trentacle 112 Junior Poster in Training

You didn't ask a question, so I'm assuming you want feedback.

  • void main() is a non-standard extension to the C language. Prefer int main(void) (or int main(int argc, char *argv[]) when you want to use command line arguments).
  • <conio.h> is also non-standard and also very very old. Don't use it or any of the functions it provides. (Clearing the screen when you have not been explicitly asked to do so is annoying to the user.)
  • fflush(stdin) invokes undefined behavior because fflush() should only be used on output streams. If you want to discard input (which is usually a bad idea anyway) then you must write your own code to do so.

  • <conio.h> is also non-standard and also very very old. Don't use it or any of the functions it provides. (Clearing the screen when you have not been explicitly asked to do so is annoying to the user.)

  • Your program will have undefined behavior and may fail when the user inputs N > 10. You need to ensure that all inputs are within the ranges your program can handle.

  • Never ever use gets(). It can be made to overflow the array it's given very easily, which causes undefined behavior. Use fgets() instead and pass in the size of the array.

You should avoid relying on non-standard features because they don't work for everyone. I didn't try to compile and run your program because I knew as soon as I saw #include <conio.h> that it wouldn't work for me as …

Trentacle 112 Junior Poster in Training
$x += $y

means the same thing as

$x = $x + y

with the exception that $x is evaluated only once -- this would only make a difference if evaluating $x had side effects (e.g. when it's not really a variable but actually a subroutine call).

You can use the same op= syntax for any of Perl's operators, like *=, -=, /=, <<=, .=, etc. and the semantics are the same.

Trentacle 112 Junior Poster in Training

Nope. The first part of a 3-statement for clause is run only once, before the first test or the first execution of the loop body. The equivalent would be more like

mytype = 500
for x in range(filearray_count):
    ...

That said, 500 seems to be somewhat arbitrary since you don't use the value of mytype within the loop -- instead, you assign to it before using it.

I would guess that 500 is a sentinel value that is impossible or unlikely to find in the actual filearray structure, and is used after the loop terminates to test whether the inner if statement ever executed. If that's the case, I'd make it a dedicated sentinel instead:

sentinel = False
for x in range(len(filearray)):
    if member in filearray[x][0]:
        sentinel = True
        print(x, filearray[x][1], member, sep=', ')

Notice I also changed range(0, filearray_count) to range(len(filearray)) and changed your print call to use a custom separator so it looks more like the Perl output -- if you need to do more fancy stuff you'd be better off with the str.format method.

If mytype needs to be the last value of filearray[x][1] printed out after the loop terminates, I'd still initialize it to None instead of 500. What's special about 500?

Trentacle 112 Junior Poster in Training

This looks odd to me:

foreach $line (@L1) {
    $line =~ s/,,,/,/g;
    print @L1;
}

Sure you want to print all of @L1 every time through that loop?

As for your output, I can't tell what you expect it to do. Could you post your input and describe what you expected to happen?

Trentacle 112 Junior Poster in Training

The question has been marked as solved, so I don't know whether you're still expecting answers...

When you find yourself calling static methods from non-static methods or vice versa, it means you haven't thought about the problem enough. You actually answered your own question after a fashion, if you take the time to consider it:

Same with the shuffle() method, that's a non-static method and I'm trying to call it from a static method, but I have to use that method to shuffle the deck

To shuffle what? A deck, which is an instance of the CardPile class. The CardPile class itself is not -- can not be -- a deck; it's more of a blueprint that describes how CardPile objects (instances) behave. You can't call CardPile.shuffle() because the CardPile class doesn't contain any cards or anything to shuffle.

What this boils down to is that within the makeFullDeck method, you must actually instantiate an object of class CardPile, with the new keyword and the constructor you wrote, and call the shuffle() method on that instance.

Making any more sense?

Trentacle 112 Junior Poster in Training

Since you're not instantiating any objects of class Die, anything you want to use must be declared static. That includes all the variables that are defined directly within the class as well as the die() method.

That said, you don't have code showing how you expect to use the Die class (namely the body of main), so I could be way off base.

Trentacle 112 Junior Poster in Training

Easiest C version, guaranteed. Probably won't work under Windows though.

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

char const * const lines[] = {
    "my %files;\n",
    "while(<>) {\n",
    "   my($index) = /(\\d+)$/;\n",
    "   $files{$index} .= $_;\n",
    "}\n",
    "for(keys %files) {\n",
    "   open OUTPUT, '>', \"File$_.txt\";\n",
    "   print OUTPUT $files{$_};\n",
    "   close OUTPUT;\n",
    "}\n",
    0
};

int main(void)
{
    FILE *script;
    char const * const *p;
    script = fopen("summarize.pl", "w");
    for (p = lines; *p; p++) {
        fputs(*p, script);
    }
    fclose(script);
    return system("perl summarize.pl");
}
Sokurenko commented: nice one ))) +2
Trentacle 112 Junior Poster in Training

Why do you need an array that size?

How would you rewrite your program so that such a large array is not necessary?

Trentacle 112 Junior Poster in Training

I'm going to partially disagree with you on that point. On the one hand, organization and documentation go hand in hand. Disorganized code can be absolutely undocumentable, and when you find yourself coding or designing something that you don't know how to document, you know when it's time to back up and think things through again.

On the other hand, I'd still rather read oddly designed code that's correctly formatted and well-documented than code that's logically structured but uses variables named value1, value2, value3 ad infinitum.

Trentacle 112 Junior Poster in Training

Schol-R-LEA has an overall good analysis. I'll comment on three points.

  • Everybody you ask will have a different opinion on what editor or IDE to use. Personally I use Vim but I usually recommend jEdit for newbies; it has a good user interface, available on anything Java runs on, and supports quite a few languages out of the box.
  • I don't recommend learning assembly unless and until you need it. It might make you a marginally better programmer, but honestly, who has the time? Having been there and back, there are more important skills to develop (see below).
  • This topic seems awfully familiar.

Regarding more important skills to develop. Quiz: What's the core of professional software development? Answer: documentation. Reading it, writing it, maintaining it. If you don't have good natural language skills, that's going to hurt you far more than any of the thousands of programming languages you don't know. Similarly, if you don't follow good commenting practice and write good design docs, you could write code that outperforms the next guy's by a factor of 1000 and it might not matter. Cheaper hardware will make inefficient code faster. Nothing will make confusing code easier to understand.

Just my $0.02

Trentacle 112 Junior Poster in Training

For values of voltage less than 4200, you'll always get zero. This is because of the way integer arithmetic works. Relevant C FAQ link.

Trentacle 112 Junior Poster in Training

Or

no strict 'refs';
$ARGV[0]->();

(This is not actually a recommendation, and I hereby disclaim any consequences of doing this in actual code, including but not limited to odd behavior, strange errors, problems debugging, write-only code, and enraged maintenance programmers.)

Trentacle 112 Junior Poster in Training

Well, congratulations! You found an unconventional solution to a common problem. If you both (a) know why it works and (b) understand why you shouldn't do that in practice, consider yourself to have made great progress today.

I'll still suggest you find a good quality book, though. The C Programming Language is an excellent guide that doesn't teach bad habits like void main().

Trentacle 112 Junior Poster in Training

Well, yeah. &sub_name; just calls the sub_name subroutine. In your example you define four subroutines and call two of them. What would you expect to happen?

Trentacle 112 Junior Poster in Training

Nope. If you want it to do something when you run it from the command line, you need to put code in the top level of the file (not in a function).

You can easily make your script behave this way, though, if you add the following code to it:

if ($ARGV[0] eq 'thisismyfunction1') {
    &thisismyfunction1;
} elsif ($ARGV[0] eq 'thisismyfunction2') {
    &thisismyfunction2;
}

It's simplistic and won't scale well, but it works if it's used as you describe. Depends on what you need.

Trentacle 112 Junior Poster in Training

That's certainly one valid way to pass multiple values to a function, but it's not advisable. Your proposed solution is overly complicated, which makes it hard to document, hard to read, and hard to debug.

Furthermore, it seems in your case to be totally unnecessary. Since you're not doing anything with the array elements but printing them out, "pass-by-pointer"[1] would work just fine, and you wouldn't risk causing any side effects by simply passing a pointer to the original array. (If you want to guarantee that you don't change the original object within the function, declare the function parameter const -- that's what it's there for.)

If, on the other hand, you want to use a function that changes the array that's passed to it, without changing the original array, then your most viable option is to make a copy of the array and pass the copy instead of the original. This is not the same as passing an array "by value", but it will usually have the same effect. You can also use the struct trick described earlier to kind-of pass an array by value -- the disadvantage being that it won't work for dynamically sized arrays.

[1]: As opposed to "pass-by-reference", which exists in C++ but not in C. In C, arguments are always passed "by value", but some values happen to be pointers, as deceptikon correctly pointed out.

P. S. What book are you using? void main() and clrscr() are non-standard, and worrisome to see because they're …

Trentacle 112 Junior Poster in Training

My industry experience is not impressive and not in your industry, so take the following with a grain of salt.

I once knew a developer for a major company who would often travel to deliver training lectures for corporate clients. You might research companies that offer training for their product lines, and look into what it takes to be successful at that. Even if it's not what you end up doing, good people skills and clear goals will make you stand out and help you establish yourself in a position to determine how much you want to travel.

Sidenote: As a student, I enjoyed IEEE membership and learned a lot of interesting things from attending meetings and conferences. You should investigate joining ACM or a similar association for software folks -- student memberships are usually cheap and come with great benefits, like access to discounted software, online libraries, jobs boards, and conferences where you can talk to real professionals about questions like yours.

Trentacle 112 Junior Poster in Training

The number of bits in a byte is also implementation-defined. C99 section 3.6p3.

Even so, your code shows nothing, since ucChar gets promoted to int before any math actually happens (unless char is unsigned and UCHAR_MAX > INT_MAX, in which case it's promoted to unsigned instead). I'm not even sure what it was supposed to be showing in the first place.

I repeat my question: What did you expect to happen when you did tempstr[2] = '50'? The comment on that line ("trying to assign '1' boolean value") doesn't explain anything and in fact just makes it more confusing.

Trentacle 112 Junior Poster in Training

Do you see why the result is 0x1.9cccccp3?

I don't think you can do any better than that with the standard library. Converting fractions into other bases is not a very common need (unlike integers, which are quite handy to have in base-N sometimes.)

What you might do with a minimal amount of coding is take the fractional part, multiply it by 16^N where N is the number of hexadecimal places you want, convert it to an integer, and output that in hex -- something like this (untested):

System.out.printf("%x.%x\n", (int)x, (int)((x - int(x))*0x1000000))

Good luck

Trentacle 112 Junior Poster in Training

I'm using VS2010 compiler. when i use as above statement it didnt give any build error. it built fine and execute fine

Cool story bro.

According to section 6.4.4.4 of C99, the behavior of a multi-character single-quoted constant like '50' is implementation-defined. A diagnostic is not required in this case, but you're still expected to know that you're relying on implementation-defined behavior (and if you want to know what the actual behavior is, it should be found in the compiler's documentation). I'm not sure what you're going for in that case anyway -- what would you expect to happen?

As for line 5, you allocated only 4 chars, but you assign to the 5th one, tempstr[4]. I suppose this is a typo, but you nevertheless invoke undefined behavior by writing off the end of an array.

Trentacle 112 Junior Poster in Training

It's int main(void)

WaltP commented: Correct. But if you're going to correct someone, explain why. It helps them learn. +14
Trentacle 112 Junior Poster in Training

You mean like

System.out.printf("%4.2f\t%4.2f\n", var1, var2);

Check out the Java API for PrintStream and Formatter to see details on printf.

Trentacle 112 Junior Poster in Training

I think I understand why -- printf("%s\n", s) can be optimized to puts(s).

That said, this is EXACTLY why you shouldn't ever rely on undefined behavior -- because it does weird things you can't predict and is affected by apparently unrelated changes in ways you can't anticipate. Any attempt to make sense of what happens after UB has been invoked is an exercise in futility.

Moschops commented: That is exactly what's happening in this case. Good skillz.. +9
Trentacle 112 Junior Poster in Training

Ok, wait.

If your first file says what position you want to change, why does your second file say what character you want to change? If the "reference" character in file 2 is different from the character found at the position given in file 1, do you still change it to the "mutant" (not "multant") form?

I might also ask, how do you do it in Excel?

Trentacle 112 Junior Poster in Training

atoi() has no way to recover from errors. Use strtol() as subith86 suggested.

Should you actually want to test whether a character is a digit, don't perform contortions; #include <ctype.h> and use isdigit instead.

Trentacle 112 Junior Poster in Training

I'm trying, but I can't figure out how your output follows from your input. Can you explain the problem more clearly?

Trentacle 112 Junior Poster in Training
WELCOME TO FORUMS, puppycrazy
WOULD YOU LIKE TO ANNOY YOUR USERS?(Y/N) : y
IN THAT CASE PLEASE CONTINUE USING ALL CAPS

WOULD YOU LIKE TO GET GOOD ANSWERS?(Y/N) : y
IN THAT CASE PLEASE CONSIDER PROOFREADING YOUR POSTS TO ENSURE THEY MAKE SENSE. ALSO,PLEASE!AVOID>USING~WEIRD.......><....PUNCTUATION, SPACES EXIST FOR A REASON
Trentacle 112 Junior Poster in Training

Hello everyone!!
I am new to Linux forum and have a question related to typecasting in C related to offset of structures. <snip>

Typecasting is something that happens to actors...

Trentacle 112 Junior Poster in Training

Generally speaking, anywhere in C you would see a call to malloc(), in Java (or C++) you'll find the word new instead. This also applies for strings, but strings are a little bit special in that there is a unique syntax for creating them (using "...") that doesn't use new. In either case, the result is the same: the standard library reserves the space to store the String when the constructor is called. Java doesn't have destructors (as such), so the space is only freed when the garbage collector gets around to it.

In C, I'd like to add, you do not need to declare the size of the char array to store a string when you initialize it with a string literal; since the size is known at compile time, the compiler can do it for you.

char str[] = "foo";
Trentacle 112 Junior Poster in Training

Careful of file extensions, too. Windows will mess you up sometimes... if you save something with the extension, make sure it saves as values.txt and not (say) values.txt.java (this shouldn't happen with any IDE I'm familiar with, but you never did say how you created the file).

Trentacle 112 Junior Poster in Training

Homework detected, even though you haven't asked a question yet.

If this were real code, I'd say go ahead and use goto. The reasons to avoid doing so don't really apply in this particular situation, and it saves time, space and clutter.

Trentacle 112 Junior Poster in Training

Have you noticed that n is only ever zero at the beginning of the program? I'm not 100% sure I understand the purpose of it, but I think you should at least reset it on each iteration of the while loop.

Furthermore, what happens when tmp ends up pointing to the head of the list? tmp isn't NULL, but tmp->prev is... that could be the cause of your segfault.

However, this is kind of convoluted for an insertion sort. Consider rewriting it.

Trentacle 112 Junior Poster in Training

I don't want to solve your homework problems for you, but maybe I can point you in the right direction.

Your problem is that findName finds only the first matching line in the file and returns, correct? So you need to make findName somehow return as many lines as are in the file. There are three ways I can think of to go about this:

1) make findName concatenate all the lines in the file, and stuff them all into serverResult;

2) make findName return more than one line at once, by changing its prototype so that it can populate an array of lines rather than just one buffer;

3) make findName return a different line every time it's called, until there are no more lines left, and revise your calling code to repeatedly call findName until it indicates by a zero return value that there are no lines in the file.

I'd probably go for option 3, although option 1 might be less work. Look up strtok for a better idea of how such a function could behave.

I'd like to add, there is a very real potential for buffer overflow in the current program, which using option 1 would only aggravate; please consider passing the size of the result buffer in so findName won't accidentally write off the end of it.

Trentacle 112 Junior Poster in Training

"Advanced Java" really doesn't mean anything. I'm guessing it's a class, something like my CS2 class, in which you're still going to be dealing with the ins and outs of the Java language. In other words, probably not looking at hibernate, spring or any of that stuff, and really only touching on the nuances of OO design. What they probably want is for you to make code that uses classes, interfaces, objects, and methods, without causing any syntax errors. For that, any book you've been assigned will probably work as well as the next, but if you can pick your own... Head First Java is an excellent choice.

If you're interested in self-improvement beyond the content of the course, I'd suggest Head First Design Patterns, which is a nice little intro to a grab bag of ideas you can use to structure your program sensibly. Be sure to read others' code as well -- reading code written by experts helps you understand how experts write code. You might move on to a framework like Spring or Hibernate, which I don't have any experience with, but have entire books written about them.

If a reference manual (i.e., a book for someone who already knows how to program in Java to look up details in from time to time) is really all you want, I've heard good things about Deitel & Deitel, but I don't have a copy myself. Java in a Nutshell might be good too; you rarely go …

Trentacle 112 Junior Poster in Training

Looks like homework.

What are the contents of data_list?

What do you need to do to each one?