deceptikon 1,790 Code Sniper Team Colleague Featured Poster

but this is the case with first element of array .. right ?

Yes, you could say that.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

please tell the answers for which this thread is started

Please explain your remaining confusion. Both Ancient Dragon and I collectively answered both of your questions.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

And even through it may be legal in standards, but when compiled in gcc it gives a segmant fault.

Are you compiling with strict conformance as C? This might just be one of those obscure areas where gcc isn't conformant yet nobody cares enough to fix it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You cannot use main as a function pointer. It is undefined behaviour.

Only in C++, C has no such restriction. Though it's commonly accepted that taking main()'s address or calling it recursively in C is stupid. C11 may have tightened up the rules for usage of main though, I'm not as familiar C11 as I am with C99 and previous revisions.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

my question is that how can we use "main" (only name without parenthesis) as the pointer to a function ? because
main() is a function. I am not getting it how is it true ?

It's syntactic convenience based on the fact that you can only do two things with a function: call it or take its address. If you're not calling a function with the () operator then you must be taking its address, and thus the address-of operator isn't necessary.

So fun(main) is equivalent to fun(&main).

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

But why does C consider *y++ to be an incremention to the adress of y?

That's just how the precedence rules work.

Is there a reasonable answer to this wierd operator precedence order?

I'm not aware of any rationale for it, though Dennis Ritchie wrote a history of C that might mention it. However, by my recollection the only mention of precedence in that history has to do with bitwise operators.

And will (*y)++ work as expected?

Yes.

@deceptikon what will u say to this statement ?

int *p,x=3;
int c=9;
p=&x;
*p++ = c;
how values are assigned/incremented in the last line ? I think i will get your point after this answer.

You're essentially overwriting x with 9, then incrementing p. Note that this increment is unsafe because pointer arithmetic is only meaningful inside an array or dynamically allocated block.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

In the first, variable declared is an extern; unless it is assigned a value the memory will not be allocated.

That's incorrect. Even for variables declared as extern, an object will be linked to it when creating the executable[1], and the object has a size that will contribute to the executable if it's stored in either the data or BSS segment.

In this case linkage is pretty much irrelevant to the question.

[1] Unless there's no actual object, in which case the linker will puke all over your code if you try to use the variable anywhere.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I didn't get one point that how can typecasting an pointer to an array of pinters into an integer pointer make it to point to the forst element in the array ?

You know that array indexing is essentially an offset from the base address of the array, right? So a[5] is equivalent to converting a to a pointer to the first element, then incrementing the pointer by 5 and dereferencing the result (ie. *(a + 5)). Well, all arrays work like that, and the base address is always the first element of the most nested dimension.

So regardless of how you interpret the address, it's always the same address. For example:

#include <stdio.h>

int main(void)
{
    int a[2][3][4];

    printf("%p\n", (void*)a);
    printf("%p\n", (void*)a[0]);
    printf("%p\n", (void*)a[0][0]);
    printf("%p\n", (void*)&a[0][0][0]);

    return 0;
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

In the first, the global array is likely to be stored in the BSS (uninitialized data) segment of the executable file itself while the local array is more likely to be drawn from the stack at runtime. Because stack space is already allocated to the executable in one way or another, local variables don't contribute extra bytes to the size of the file.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The difference between using refrences(&var), and pointers(*var) is that using refrences is more efficent because you do not have to derefernce the object.

While there's potential for such an optimization, I wouldn't rely on it. The benefit of references is largely syntactic convenience (for more than you probably expect).

Am I right, and if I am why use pointers then?

Pointers can point to nothing, references cannot. This may seem like a minor thing, but it's actually pretty big. Pointers can also be reassigned to point to another address while references are stuck. Changing the "thing" being aliased is pretty critical when using pointers for things such as linked data structures. And of course, dynamic memory specifically works with pointers, so at the very least you'd need to remove and add indirection to work with it as references (not recommended).

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

When you say *p++, what really happens is *(p++). So you're evaluating to the value pointed to by p, and then incrementing the address stored in p. So let's break it down:

y = &x;

The address stored in y is 500 (going off your original stated assumption for simplicity).

z = y;

The address stored in z is 500. Now y and z both point to x.

*y++ = *z++;

The value stored in the object pointed to by z is copied into the object pointed to by y. After this happens, both y and z are incremented by 4 bytes (ie. the assumed size of an int). Note that the assignment is directly equiavelent to x = x, because both y and z point to the same address.

x++;

The value stored by x is incremented to 31.

printf("%d %d %d",x,y,z);

The output will be 31, 504, 504. All variables involved were incremented one time. For x that means the value 30 becomes 31, and for the two pointers, the increment skips the address value ahead by the number of bytes in the pointed to type. Since int is assumed to be 4 for this example, 500 becomes 504.

Ancient Dragon commented: excellent :) +14
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You'd probably get a compiler error about implicit conversion between incompatible types.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The cast is defined. The way you use the resulting pointer could be defined or undefined. I wouldn't call it good or bad, but the cast does raise warning flags such that I'd question it in a code review.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The address produced by using arr in value context is then reinterpreted as a pointer to int, which can then be dereferenced to get the value stored at arr[0][0][0]. This particular cast is safe, at least until you decide to iterate over all of the items:

int arr[2][2][2] = {1, 2, 3, 4, 5, 6, 7, 8};
int *q = (int*)arr;
int i;

/* Please don't do this */
for (i = 0; i < 8; ++i)
    printf("%d\n", *q++);

While this type of punning of multidimensional arrays into 1D arrays usually works, it's technically undefined by the C standard.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

That's by design. Unverified and newbie members aren't allowed to create new tags, only use existing ones. You probably crossed the threshold between a newbie member and a community member (these are our terms for the permissions levels) in those three hours.

By the way, the criteria for promotion from newbie member to community member is 5 or more posts + 5 or more days of membership or 15+ reputation points. Judging by your stats, I'm going to guess that it was the post threshold that you hadn't crossed yet.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Not clear at all, try giving me an example.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What do you mean "with some other types"?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You can create a pointer to an incomplete type. In fact, that's precisely what happens with the node pointer member here:

struct node {
    int data;
    struct node *next; /* struct node is an incomplete type here */
};
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Yes, that seems correct.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

please explain the reason also.

Um...because that's the way the designers wanted it? It makes sense for a qualifier on a typedef'd type to apply to the object of that type rather than some random part of that type. This is consistent with the behavior of const in the absence of typedef, and consistency is a good thing.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Nevermind, I'm wrong. The const applies to the whole of the typedef, so this:

const hello ptr1, ptr2;

Is equivalent to this:

char * const ptr1;
char * const ptr2;

Sorry for the misleading information, I'll blame it on rarely using constant pointers and never wrapping pointers in a typedef. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

This:

const hello ptr1, ptr2;

Is equivalent to this:

const char *ptr1, *ptr2;

And this:

const char *ptr1;
const char *ptr2;

And as we already know, it's the pointed to value that's const in these cases, not the pointer. To make the pointer const, and thus unable to point to any address other than the one originally assigned, but not the pointed to value, you'd do this:

char * const p = /* An initializing address */;

To make both const:

const char * const p = /* An initializing address */;

Confused yet? Do you hate C's declaration syntax yet? If not, don't worry...you will as soon as you start working with pointers to functions and pointers to arrays. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If you have any ideas for a code snippet you'd like to see, please post them here. We can't depend on the snippet writers to come up with all of the ideas, can we? ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Hello Qonquest, unfortunately you no longer have the legal right to use the code you have written. By posting your code, you have granted DaniWeb an exclusive copyright license to your code according to DaniWeb's terms of service. You may no longer use it and have no rights to you code. Please delete your code from your computer.

If you're trying to be funny, it's in very poor taste. If you disagree with the policy as it's written, please start a thread in the feedback forum to encourage changes rather than employing back stabbing techniques in places Dani isn't likely to see.

happygeek commented: well said +11
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

My bad, I missed that bug too. Instead of comparing against srclen, it should compare i against the size of the result to avoid buffer overflow. But since this is clearly homework and that kind of robust error checking is both unnecessary and would result in further changes to the code, just use the condition to stop at the end of dst:

#include <stdio.h>
#include <string.h>

void Problem8(char dst[], char src[]);

int main(void)
{
    char src[] = "This is a source string";
    char dst[] = "This is a destination string";

    Problem8(dst, src);
    putchar('\n');

    return 0;
}

void Problem8(char dst[], char src[])
{
    int dstlen = strlen(dst);
    int srclen = strlen(src);
    char result[60];
    int i, j;

    for (i = 0; i < srclen; i++)
    {
        result[i] = src[i];
    }

    for (i = srclen, j = 0; j < dstlen; i++, j++)
    {
        result[i] = dst[j];
    }

    for (i = 0; i < srclen + dstlen; i++)    
    {
        printf("%c", result[i]);     
    }

    result[i] = '\0';
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Object will always be involved, I think you meant to say: it's not Directly inherited.

I did say that:

when you explicitly extend a class, Object isn't involved except as a base of the class being extended

Though I'll readily admit that the wording isn't my best. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Actually, I was sorely tempted to reply with cliffs of your post for people who didn't want to read all of it, but decided it would be taken negatively and chose not to do so.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Thank you for at least replying! But, I must say to reply to something without reading is like learning to program without a purpose. Think positive!<3

I carefully read your first post this morning but didn't reply. Does that count? ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It would be hard to read a file if you dont know the size.

Well, it's not a one-liner, but not unusually difficult. I don't disagree that this is a sticking point, but even C++ isn't a good language for string processing. C is even worse at it.

I am trying to find a programming language that is right for me.(Trust me i know how weird that sounds).

That doesn't sound weird at all. I've experimented with some obscure languages in my time. ;)

In your opinion what is a better language. C or C++.

C, no contest. C++ has a few niceties that I miss when working with C (std::string being one of them), but it also has a heaping pile of doo-doo that I don't miss. So the simplicity and elegance of C is a net win, in my opinion.

And is C++ so called OOP really going to be a bigger hit then C?

C++ is already a bigger hit than C, mostly because it makes for cleaner modeling of large systems.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

So whats is C equivalent of a C++ string?

There isn't one. You could go out and find a third party string library like bstring, but unlike std::string, you don't have the option of a standard string "class" in C.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

In your second loop you have this:

intConcatenatedStringIndex = (intLengthOfSource + 1)

That's wrong, and it introduces an off-by-one error by setting intConcatenatedStringIndex one element too far. You'll have better results (and not an invervening garbage character) by initializing the index to intLengthOfSource without any changes.

On a side note, your excessively verbose naming convention is difficult to read. Compare your code with the following, which is pretty much identical except it uses shorter and more conventional names, and also has minor tweaks to maintain consistency (I also fixed a bug in the second loop's condition where only the latter condition was driving the loop):

void Problem5(char dst[], char src[])
{
    int dstlen = strlen(dst);
    int srclen = strlen(src);
    char result[60];
    int i, j;

    for (i = 0; i < srclen; i++)
    {
        result[i] = src[i];
    }

    for (i = srclen, j = 0; i < srclen && j < dstlen; i++, j++)
    {
        result[i] = dst[j];
    }

    for (i = 0; i < srclen + dstlen; i++)
    {
        printf("%c", result[i]); 
    }

    result[i] = '\0';
}

Finally, guessing that Problem5 really means writing your own version of strcat(), here's an implementation that's a bit more realistic and follows the interface and behavior of strcat() more closely:

char *concatenate(char dst[], const char *src)
{
    char *end = dst + strlen(dst);

    while (*end++ = *src++)
        ;

    return dst;
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

So can i create this??

Not as such, no. The best you can do without massive amounts of preprocessing (whch C++ started out as, on a side note) is defining your own type as a structure and creating functions to work with it.

And can i modify existing types such as int?

No, and I'm truly thankful for that because nobody in their right mind would alter the syntax or behavior of built-in types.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I want to ask that as I use int, float etc datatypes in coding can i modify them.

I still don't understand. You can choose an existing type to interpret the argument as, and it gives you a value (or invokes undefined behavior if you ask for an incompatible type). From there you can do whatever you want with the value.

As in the MyPrintf() example, you can use something like a format string to figure out what type to use in va_arg(), because that type is hard coded.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I hate to be "that guy", but if you made it this far and still can't produce even a vague idea given the entire field of computer engineering, you probably don't deserve to graduate.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Please post a complete program along with starting values for the variables. I'd make an educated guess that you're dividing by zero, but that's pure speculation given your lack of detail.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

va_arg( aptr, double )
where does the data type definitions are stored and can i modify them?

I don't understand the question. va_arg() takes the next value from the variable argument list and interprets it as the type you pass for the second argument. So in va_arg( aptr, double ), the next argument is interpreted as a value of type double and "returned" for your use.

Let's simplify a bit. Here's a bare bones variable length argument function. It requires that all variable arguments be of type int:

#include <stdarg.h>
#include <stdio.h>

void foo(int n, ...)
{
    va_list args;
    int i;

    va_start(args, n); /* Start pulling varargs after n */

    for (i = 0; i < n; ++i)
        printf("Arg #%d: %d\n", i + 1, va_arg(args, int));

    va_end(args);
}

int main(void)
{
    foo (5, 11, 22, 33, 44, 55);

    return 0;
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

read that every class extends a object class by default.

Yes.

then it should cause multiple inheritence and must not be supported by Java.

Think of it like this: when you explicitly extend a class, Object isn't involved except as a base of the class being extended. When you don't explicitly extend a class, Object is automagically extended. Thus it's always single inheritance, but the extending class ultimately has a base of Object at the very top.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I found this unique program which will allow the user to create his own format specifier which will use "%b" as format specifier to convert a integer directly into binary.

Hardly unique, it's just another naive implementation of printf() that adds specifiers at the author's whim. Not that it isn't useful for learning how variable length argument lists are implemented, of course.

I want to know more about this code.

What do you want to know? I've implemented printf() for real (as in fully conforming to the C standard), so I can probably answer any questions you have about how it works under the hood.

However, I'm disinclined to give you a lecture about how the code works and why, so I'll kindly request that you ask some specific questions for me to answer.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The problem is that indexings() takes its parameters by reference rather than by value or const reference. Unfortunately, there's not really a fix for that unless you remove the updating of totals and put it somewhere else. For example:

for (vector<Student_info>::size_type i = 0; i < students.size(); ++i)
    students[i].totals = grade(students[i].midterm, students[i].final, students[i].homework);

sort(students.begin(), students.end(), indexings);

Where indexings() is modified such that the only thing it does is a comparison:

bool indexings(const Student_info& A, const Student_info& B)
{
    return A.totals < B.totals;
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Your paraphrasing of the output is incorrect, and that hides a critical piece of information in figuring out what's wrong. Specifically "Book Number : A100" would not be part of the output. The output for A200 would actually be:

Enter ISBN : A200
Book Number : The_Book_of_life
Book Title : Me
Book Number : A200
Book Title : My_House
Author : You

Notice how the number of the first "match" is actually the name, and the title is the author. This suggests that your process for moving through the file is resulting in false positives.

Following that logic, it's easy to see that by constantly incrementing x (when it's clearly intialized to 0), eventually you'll hit a number that places execution inside the conditional statements regardless of the current value of Data. The solution is to use direct comparison in all cases and not try to be clever with a global counter. For example:

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

vector<string> split(const string& s, char delim)
{
    vector<string> result;
    istringstream iss(s);
    string part;

    while (getline(iss, part, delim))
        result.push_back(part);

    return result;
}

int main()
{
    ifstream in("test.txt");

    if (in) {
        string line;
        string isbn;

        cout << "\n\n\tEnter ISBN: ";
        cin >> isbn;

        while (getline(in, line)) {
            vector<string> parts = split(line, ' ');

            if (parts.at(0) == isbn) {
                cout << "Book Number: " << parts.at(0) << '\n'
                     << "Book Title: " << parts.at(1) << '\n'
                     << "Book Author: "
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

A solution to the trawling through posts seperating sigs from images could plausibly be solved by an option in user config to turn on/off display of such imagery in signatures. So if your not interested in seeing them you wouldnt.

That option is already available, though it also includes hiding avatars along with signatures in their entirety.

I'd like to split it into two separate options (one for avatars and one for signatures) because I personally use avatars as a primary way of identifying members. ;) But given the current restrictions on signatures, that's a battle not worth fighting with Dani to approve. At present the hiding feature is really more for page load performance than anything.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

i keep getting errors after adding fgets.

Nobody can help if you don't post your code or tell us what the errors are.

i have no idea how to put the storage properly since the number at start is the line number and the operation in the line thus that why sscanf is needed but i have no idea how to do it

In my infinite generosity, I'll offer you a basic example that parses the specified file into tokens using fgets() and sscanf() then prints the result accordingly. I also added the capability for including comments and blank lines (which are ignored):

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

#define COMMENT_START ';'
#define MAX_ARGS 2

void panic(const char *message)
{
    perror(message);
    exit(EXIT_FAILURE);
}

char *skip_ws(char *s)
{
    while (isspace(*s))
        ++s;

    return s;
}

int main(void)
{
    FILE *in = fopen("test.txt", "r");

    if (in) {
        char line[BUFSIZ];

        while (fgets(line, sizeof line, in)) {
            char args[MAX_ARGS + 1][10] = {0};
            char instruction[10];
            char *p = line;
            int lineno, argno;
            int i, n;

            p = skip_ws(p);

            /* Skip blank lines and comments */
            if (*p && *p != COMMENT_START) {
                /* Extract the line number and instruction */
                if (sscanf(p, "%d: %9s%n", &lineno, instruction, &n) != 2)
                    panic("Invalid instruction line");

                printf("Parsing instruction '%s' on line %d\n", instruction, lineno);

                /* Move to the first potential argument */
                p = skip_ws(p + n);

                /* Extract instruction arguments */
                for (argno = 0; argno < MAX_ARGS; ++argno) {
                    if
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Assuming you mean a C++ keyword, the list is short. Just store all of them in an array and do a lookup comparison.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What are the for/against's for such implementation on the site? Assuming database related or the content that the less mature individuals would put in the signatures.

Signatures are limited in size so that they aren't obtrusive and take away from the thread. I've been on a few forums where images were allowed in signatures and you could have a 20 line signature on top of it. It was all very distracting when trying to separate the content of posts from flashy signatures.

There really aren't any technical issues for allowing images beyond adding that feature to the profile editor. Images aren't stored in the database as blobs or anything, we keep them in the file system and store references. Displaying them is a trivial matter, and we've already done the work of uploading and embedding images as part of the post editor (so it's a fairly simple port).

Any hesitation about adding this feature would be potential for abuse versus benefit to the community. While I'm not against image signatures and might actually use them myself, I honestly can't say whether such a feature is worth the effort. I can't recall seeing any requests for it other than yours in over 7 years here. Then again, my memory isn't exactly stellar. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Here we used getch() which is not standard. How should I code without using getch() ?

There's no standard way to simulate getch(). Pick your favorite non-standard option to replace it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

@deceptikon what should i read in this for getting my answer ?

All of it. Just getting the answer to your immediate question won't stop you from making a similar but seemingly unrelated mistake with floating-point in the future. So it behooves you to study up on the representation and behavior of floating-point in general.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Put simply, if the application isn't intuitive, people won't use it unless they're forced to do so. If they need to refer to a manual, the application isn't intuitive. If they need to go to a class, the application isn't intuitive.

In your shoes, my first line of attack would be to shadow users as they actually use the application to accomplish real work, since they're clearly either too timid to complain or not interested in using the application in the first place. I wouldn't offer advice beyond answering pointed questions, just take notes on where they seem to be having trouble. From there I'd have a better idea of what needs to change in the user interface to make the application more friendly.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

name_.first(firstName), name_.second(lastName)

C++ doesn't support initializing individual members of a member object in the initializer list. Ideally you'd want to add a constructor to the Name class that takes a first and last name, then write the initalizer list like this:

explicit Student(const std::string& id, const std::string& firstName, const std::string& lastName)
    : id_(id), name_(firstName, lastName){

    if(!isValidId(id) || !isValidName(name_)){
        throw "Student::Student(const string&, const string&, const string&): invalid input.";
    }
}

Otherwise, as Ancient Dragon mentioned, you'll need to eschew the initializer list and do a straight assignment in the constructor body:

explicit Student(const std::string& id, const std::string& firstName, const std::string& lastName)
    : id_(id){

    name_.first = firstName;
    name_.second = lastName;

    if(!isValidId(id) || !isValidName(name_)){
        throw "Student::Student(const string&, const string&, const string&): invalid input.";
    }
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I need a code which can solve the equations like this :-
56*78+(78/8)

Nobody is going to just give you the code. To do it properly would involve writing essentially a tiny compiler for mathematical expressions where you tokenize the line, convert it into an expression tree, and parse that tree to evaluate the result. It's not especially difficult, but not trivial either.

A google search will work wonders.