Narue 5,707 Bad Cop Team Colleague

I don't know what happened and I'm sure that reason is scanf().

Then let's start by using scanf() correctly. When your choice variable is a short int, the correct format specifier is %hd . Fix that and return if the problem persists.

Narue 5,707 Bad Cop Team Colleague

If you understand, you can figure out now why I'm naming the title "nested pointer", right?

I was pretty confident that I knew why just from reading the title.

I'm thought of this "timeline" of process happen in my code...

note: see my attachment for better picture of each explanation.
 
a. '1000' assigned to "value_1"
 
b. "pointer_1" become a point to "value_1" content, where:-
        - *pointer_1 == value_1's content
        -  pointer_1 == value_1's address
 
c. "pointer_2" become a point to "pointer_1" content, where:-
        - **pointer_2 == value's content
        -  *pointer_2 == pointer's content == value_1's address
        -   pointer_2 == pointer_1's address

If I were your teacher, I'd give you perfect marks for this.

The references operator, usually known as, "& == address of"... At first, I thought the equation is literally descriptive, but then I discover I'm wrong. When this operator assigned to the pointer, it will return address to the "standard variable", but not only that, it return the whole content of the address.

Now you're getting into nonsensical territory. The address-of operator is literal. It evaluates to the address of an object, and a pointer object isn't treated differently. The problem with pointers and addresses is people get confused because a pointer is both an object with an address and an object that stores an address. So for an initialized pointer there are two addresses and two values involved:

  • &ptr : The ptr object's address.
  • ptr : The ptr object's value (the pointed-to …
mike_2000_17 commented: great +14
Narue 5,707 Bad Cop Team Colleague

But some companies are partners with microsoft (which I think is pathetic).

The bold part of your statement (emphasis added by me) suggests that you have a strong bias against Microsoft which is probably coloring your opinion of .NET for web development. If you hadn't called Microsoft partners pathetic then your opinion on .NET versus PHP would be more credible.

Narue 5,707 Bad Cop Team Colleague

However, now I have a problem with my looping because this way, I am seeing the last line *TWICE* in my output

This is precisely the reason why feof() shouldn't be used as the only loop condition. It only returns true after you've tried and failed to read from the stream, which means the last record will be processed twice. fgets() can be used directly as the loop condition because it returns NULL on any kind of failure (including end-of-file):

while (fgets(LineBuffer, BUFFERSIZE, infile) != NULL)
{
    printf("%s", LineBuffer);
    fprintf(outfile, "%s",  LineBuffer);
}
Narue 5,707 Bad Cop Team Colleague

Is there a simpler way to do this(less strings, without strcat)?

I'd do it more like this:

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

int main(void)
{
    char buf[BUFSIZ];
    
    printf("Enter a floating-point value: ");
    fflush(stdout);
    
    if (fgets(buf, sizeof buf, stdin) != NULL) {
        double value;
        char *end;
        
        /* Trim the newline, if any */
        buf[strcspn(buf, "\n")] = '\0';
        
        /* Validate the string, we'll also need the value later */
        value = strtod(buf, &end);
        
        if (*end == '\n' || *end == '\0') {
            char *radix = strrchr(buf, '.');
            size_t precision = 0;
            
            if (radix != NULL)
                precision = strlen(radix + 1);
            
            printf("%.*f\n", precision, value);
        }
    }
    
    return 0;
}

That's not necessarily simpler, but it's more robust.

Also, could you explain what does %.*f actually mean? I mean, * is usually used for pointers.

In a printf() format string, * is a placeholder for some part of the field width. So %*d would print an integer where the field width is specified by another argument:

// These two calls are functionally identical
printf("%5d\n", 123);
printf("%*d\n", 5, 123);

See this.

Narue 5,707 Bad Cop Team Colleague

I don't need that kind of an example because I know how to use atof.

One of your posts suggested otherwise, which is why I suppose someone posted an example for you.

I think the question is really simple.

It is really simple. The first reply gave you the steps you need to perform: "Read the number as a string. Count the decimals. Convert the string to your double."

There is no "work" here.

Then why haven't you completed it yet? :D

And also, I asked why doesn't the following code work.

You forgot to include <stdlib.h>, and you're still printing a whole floating-point value. The value needs to be formatted correctly in the printf() format string, which is why you need to count digits initially:

printf("%.*f\n", precision, a);

Otherwise you don't know what value to use for precision . This is yet another case of misunderstanding the difference between internal and display representations.

Narue 5,707 Bad Cop Team Colleague

What would happen if I (somehow) made an enum bigger than unsigned int?

The compiler will attempt to adjust the underlying type according to the largest enumerator value. As for defining an enumerator value lager than the largest possible integer, good luck trying. ;)

Narue 5,707 Bad Cop Team Colleague

Well, that is not even close.

It's an example of how to convert a string to double, which is a necessary step in the solution to your problem.

Don't expect someone to do all of your work for you.

Narue 5,707 Bad Cop Team Colleague

I've been trying to make a reliable IRC client for a while now, and I know very little about sockets.

Am I the only one who finds this sentence semantically humorous? :D

How is the program to know the server will send three or four lines before I should send the NICK/USER ?

I'm not familiar with the underlying protocols specific to IRC, but have you considered a header packet with necessary bookkeeping information?

Narue 5,707 Bad Cop Team Colleague

Is this compilable? (i.e without the white space)

Yes, that particular annoyance was removed in C++11. The OP's compiler (Visual C++ 2010) supports the new feature.

frogboy77 commented: Thank you. Need a new compiler. +6
Narue 5,707 Bad Cop Team Colleague

So can you please explain how to use this std::vector?

Certainly. Here's a rough facsimile of your code using std::vector:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    int a, b;
    
    cout << "Enter the size for the 2D array: ";
    
    if (cin >> a >> b) {
        vector<vector<int>> vec(a, vector<int>(b));
        int k = 0;
        
        for (int i = 0; i < a; i++) {
            for (int j = 0; j < b; j++)
                vec[i][j] = k++;
        }
        
        for (int i = 0; i < a; i++) {
            for (int j = 0; j < b; j++)
                cout << vec[i][j] << ' ';
                
            cout << '\n';
        }
    }
}

The only real difference is in the constructor where you need to build up both dimensions. This is the proper way to do it if you already know the sizes, but you can grow the vector dynamically as you go if necessary, that's where the real power lies:

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

using namespace std;

int main()
{
    vector<vector<int>> vec;
    string line;
    
    cout << "Enter a table (EOF to finish):\n";
    
    while (getline(cin, line)) {
        // Insert a new row to the vector
        vec.push_back(vector<int>());
        
        istringstream iss(line);
        int x;
        
        while (iss >> x)
            vec.back().push_back(x);
    }
    
    for (int i = 0; i < vec.size(); i++) {
        for (int j = 0; j < vec[i].size(); j++)
            cout << vec[i][j] << ' ';
            
        cout << '\n';
    }
}
PrimePackster commented: Thank U very much. That helps a lot +0
Narue 5,707 Bad Cop Team Colleague

I kind-of get the impression this is a dynamic-allocation-related assignment

It's not obviously homework, but even if it were, we would be doing the student a disservice by not mentioning the better alternative for future projects.

Narue 5,707 Bad Cop Team Colleague

I hear it's technically legal under newer standards, but not every compiler supports the newer standards yet.

Not in C++. The current C standard (C99) supports variable length arrays, but they're an abomination and shouldn't be used. C++ doesn't support variable length arrays in any form because the standard library handles all but the most niche of VLA use cases.

To have a truly reliable (portable) implementation, it's better to explicitly use dynamic allocation.

Or implicitly use dynamic allocation with std::vector. You're doing the same thing with fewer features and a greater chance of implementation bugs.

Narue 5,707 Bad Cop Team Colleague

Done.

Narue 5,707 Bad Cop Team Colleague

does this works in turbo c?

Change the name of the compiler to whatever you want.

am not sure that "gss" is used in turbo c

"gcc" refers to the GCC compiler.

My sir said once about this as it will be in visual c++

Visual C++'s compiler is called cl.exe.

well Narue what is 'cmd' in this code?

A string! Read up on sprintf(). The idea is that we need to build a command line statement that invokes a compiler with the specified file name.

I tried it but its saying "undefined symbol".

Duh. I posted a snippet, it's your job to fill in the blanks and make it compilable.

Narue 5,707 Bad Cop Team Colleague

Can we (compile and execute) or just execute a c file from another c file?

Yes. The easiest way would be to simply execute the compiler with the source file as input:

sprintf(cmd, "gcc %s", filepath);

system(cmd);       /* Compile */
system("./a.out"); /* Execute */

Otherwise you're looking at running the code through an interpreter of some sort, which could be as simple as using an existing interpreter similar to above, or writing a form of eval() that handles C code (not a task taken lightly).

Ultimately, I'd say that C probably isn't the correct choice of language if dynamic evaluation of code is a necessary feature.

Narue 5,707 Bad Cop Team Colleague

Can that cause problems?

<sarcasm>
No, we just arbitrarily picked something to bash because it makes programming seem more like a voodoo art. :icon_rolleyes:
</sarcasm>

I should declare local variables instead?

You should declare variables with the smallest scope possible.

Narue 5,707 Bad Cop Team Colleague

Anyway, about the global variables, is that a wrong method?

Variables should have the smallest scope possible. Global variables are especially troublesome because they're visible and usable across the entire program, even areas that don't need access.

Narue 5,707 Bad Cop Team Colleague

Case matters in C. Both printf() and scanf() are all lower case, you're trying to use functions that don't exist.

Narue 5,707 Bad Cop Team Colleague

I am pretty sure that I'm not doing something wrong with this code.

You forgot to include <string>, and the code also does nothing with user after the input call. The following offers some corrections, though your use of global variables is still questionable:

#include <iostream>
#include <string>
 
using namespace std;
 
int money = 1000;
string user;
 
int main()
{
    cout << "Enter username." << endl;
    cin >> user;
    cout << "Welcome, " << user << "!" << endl;
    cout << "You have : " << money << " dollars left.\n" ;
}
Narue 5,707 Bad Cop Team Colleague

@Narue: Is there a way I can use toupper() with a string then?

Yes, the way you do everything with each character of a string: use a LOOP!

int i;

for (i = 0; line[i] != '\0'; i++)
    line[i] = toupper(line[i]);
Narue 5,707 Bad Cop Team Colleague

You are trying to print a character as a string:

printf("your quote was : %s",ch);

I'm not sure why toupper doesn't work with my IDE but try this:

printf("your quote was : %s",toupper(line));

toupper() returns a single character...

Narue 5,707 Bad Cop Team Colleague

While fgets() suggests reading from a file, you can pass stdin as the stream for user input.

Narue 5,707 Bad Cop Team Colleague
printf("%s\n", "hai welcome..." + 3);
Narue 5,707 Bad Cop Team Colleague

Can you be more specific? "Leaving the first three characters" is ambiguous. Do you want to print only the first three characters of a string, or all characters except the first three?

Narue 5,707 Bad Cop Team Colleague

It's possible to "catch" a segmentation fault with a signal handler, but you can't resume the program after the handler runs, so it's not very useful other than terminating gracefully. In your case the better option is to fix the bug that caused the fault in the first place. :icon_rolleyes:

Narue 5,707 Bad Cop Team Colleague

I mean you started two closely related threads on the same program. There's no need for two separate threads which ultimately would result in duplicated effort by the helpers.

Narue 5,707 Bad Cop Team Colleague

Threads merged.

Narue 5,707 Bad Cop Team Colleague

Would the last line work?

No.

Or would I have to declare a function to execute that last line?

Yes. However, note that you can initialize sasd to that expression in the global scope:

int vap = 7;
int pav = 2;
int sasd = vap * pav;
Narue 5,707 Bad Cop Team Colleague

i donot know what to do can u explain me by the help of code please.

You have no choice but to make sure the source string passed to strtok() is modifiable. That means either storing it initially in an array:

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

int main(void)
{
    char src[] = "asim.nazeer.helo.me";
    char *tok = strtok(src, ".");
    
    while (tok != NULL) {
        printf("'%s'\n", tok);
        tok = strtok(NULL, ".");
    }

    return 0;
}

Or making a copy if you don't control the string provided or need to retain the original string for any reason:

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

void foo(const char *s) // Assuming no control over s
{
    char *copy = malloc(strlen(s) + 1);
    char *tok;
    
    if (copy == NULL)
        return;
        
    strcpy(copy, s);
    
    for (tok = strtok(copy, "."); tok != NULL; tok = strtok(NULL, "."))
        printf("'%s'\n", tok);
}

int main(void)
{
    char *src = "asim.nazeer.helo.me";

    foo(src);

    return 0;
}
Narue 5,707 Bad Cop Team Colleague

It would appear that the memory space on which the string is stored is not modifiable.

Correct. String literals are defined as read-only by the language, and strtok() modifies its argument.

Narue 5,707 Bad Cop Team Colleague

I don't know what you mean by rogue opening paren.

Count the parens. Two opening, one closing. Do I have to hold your hand the whole way?

Plus I get this error, I don't know what this means:

Prior to C99, you couldn't declare a variable in the initialization clause of a for loop. GCC doesn't enable C99 mode by default, yet your code uses that feature here:

for(int i = 0; i < c; ++i)

and here:

for(int i = 0; i < 5; i++)
Narue 5,707 Bad Cop Team Colleague

What do you mean?

If you don't see it after it being pointed out, I'd recommend re-reading your chapter on functions:

void prefix((char x1[]; char x2[])

Parameters are separated by a comma, not a semicolon, and you have a rogue opening paren.

Narue 5,707 Bad Cop Team Colleague

Your prefix() function signature is jacked up. Fix that and you'll get other errors that are easier to fix.

Narue 5,707 Bad Cop Team Colleague
char a[ITEM_SIZE];

if (fgets(a, sizeof a, stdin) != NULL)
    push(a, sizeof a);

pop(a, sizeof a);
puts(a);
Narue 5,707 Bad Cop Team Colleague

It depends on how you're storing the items of the stack. Personally, I would use an array of structures:

struct item {
    char a[ITEM_SIZE];
};

struct item stack[STACK_SIZE];
size_t top = 0;

With that setup, pushing and popping are a simple matter of copying the contained array:

void push(const char a[], size_t size)
{
    if (top >= STACK_SIZE)
        return;

    if (size > ITEM_SIZE)
        size = ITEM_SIZE;

    memcpy(stack[top++].a, a, size);
}

void pop(char dst[], size_t size)
{
    if (top == 0)
        return;

    if (size > ITEM_SIZE)
        size = ITEM_SIZE;

    memcpy(dst, stack[--top].a, size);
}
Narue 5,707 Bad Cop Team Colleague

You can chose between speed or space.

Or you can choose clarity. Given that we're talking about ten numbers in the range of 0 to 100, either method will be fast enough and space thrifty enough.

Narue 5,707 Bad Cop Team Colleague

For each number you read, loop over all of the numbers presently read into the array and compare with the number. If there's not a match, append the number to the array. Repeat until the array contains ten numbers.

Narue 5,707 Bad Cop Team Colleague

Because it's a 16-bit compiler designed for MS-DOS in the 80s? Grow up and use a modern compiler, or stop whining and downgrade your OS to something closer to the Turbo C era.


p.s. For those of you who are tempted to chime in that Turbo C can be run successfully on Windows 7, stuff it. It's well past time for Turbo C to die, so put away the defibrillators and let it go peacefully. The longer we cater to stupid people trying to use compilers from the age of shoulder pads and slap bracelets, the longer it will take for legitimate advances over the last twenty years to be adopted.

Narue 5,707 Bad Cop Team Colleague

It's simply leads to more memory consumption....

Properties don't consume memory in the object, they're a form of method that acts like a field.

Somebody says that,it provides security,but here still anyone can edit the value of PI. Then how we can say it as a secured one....

If you write properties that expose fields completely then there's no security benefit over public fields. However, consider this modified property:

public double PI {
    get {
        if (!_piGenerated) {
            _pi = GeneratePi(_piPrecision);
            _piGenerated = true;
        }

        return _pi;
    }

    private set { _pi = value; }
}

Now the set isn't accessible outside of the class, and the get performs some internal logic that doesn't matter to users of the property. This is the power of properties, you can get method-like behavior with field-like syntax.

Narue 5,707 Bad Cop Team Colleague

That seems kind of silly to me. The point of a checksum is to verify the legitimacy of a file after downloading it. If you're getting the checksum before downloading the file it's no different from taking on faith that the file is legit in the first place.

Narue 5,707 Bad Cop Team Colleague

Do you need to retain the original order? The standard library has a set_intersection() function that does what you want, but both sets need to be sorted:

#include <algorithm>
#include <iostream>
#include <iterator>

using namespace std;

template <typename T, int N>
int size(T(&)[N]) { return N; }

int main()
{
    int a[] = {1,2,2,3};
    int b[] = {3,5,1,2};
    
    sort(a, a + size(a));
    sort(b, b + size(b));
    
    set_intersection(a, a + size(a), b, b + size(b), ostream_iterator<int>(cout, " "));
    cout << '\n';
}

Without the ordering requirement, the linear intersection algorithm doesn't work. The naive non-ordered algorithm uses a more brute force (and thus less efficient) approach with nested loops:

for i = 0 to size(a)
    for j = 0 to size(b)
        if b[j] = a[i] and not contains(c, a[i])
            append(c, a[i])
        end if
    loop
loop
Narue 5,707 Bad Cop Team Colleague

I searched all over the net trying to find the reason behind why numbers are illegal as first characters in naming identifiers in C++, they say its illegal but they don't say why its illegal

Leading digits would be confused with numeric literals. If you allow leading digits then that would require further restrictions on subsequent characters to ensure that the literal logic doesn't find a false positive, which complicates the language definition on top of complicating the compiler by making it do unnecessary validation.

Narue 5,707 Bad Cop Team Colleague

Hmm, I'd say that a good solution is to rewrite your reverseString() entirely so that it builds the reversed string rather than tries to fill a caller provided object:

#include <iostream>
#include <string>

using namespace std;

string reverseString(string::const_iterator first, string::const_iterator last)
{
    if (first == last)
        return string();

    return reverseString(first + 1, last) + *first;
}

int main()
{
    string userString;

    cout << "Please enter a string you would like to see reversed." << '\n';
    cout << "Enter a string: ";
    
    if (getline(cin, userString)) {
        string reversed = reverseString(userString.begin(), userString.end());
        
        cout << "The contents of the string you entered is: " << userString << '\n';
        cout << "The contensts of the reversed string is: " << reversed << '\n';
    }
}

Greatly simplified, no?

Narue 5,707 Bad Cop Team Colleague

I suspect that it was trying to free a pointer that doesn't exist which kind of doesn't make sense.

This is a case where I don't see an immediate problem. It would probably take some debugging, but as I cannot reproduce the error, I can't help too much. It's a shame, because I'd be interested to know exactly what's causing your error.

I know it's important to free buffers we don't need anymore from the memory but do we need to free(src)?

Unless the process lives for a long time, it's not technically necessary. On modern operating systems the memory allocated dynamically will be freed when the process terminates. However, one can't determine conclusively how library functions such as split_str() might be called, so it's an excellent idea to clean up after yourself.

You can get rid of the allocation entirely (and thus the need for free()) by assuming that s is modifiable. This puts the onus on the caller to refrain from calling split_str() with something like a string literal. The reason for that is strtok() modifies the source string, and string literals are read-only:

char **split_str(char *s, const char *delim)
{
    /*
      Error handling omitted for brevity
    */
    char **dst = malloc(sizeof *dst);
    char *tok = strtok(s, delim);
    size_t n = 0;

    while (tok != NULL) {
        dst = realloc(dst, ++n * sizeof *dst);
        dst[n - 1] = copy_str(tok);
        tok = strtok(NULL, delim);
    }

    dst[n] = NULL;

    return dst;
}
Narue 5,707 Bad Cop Team Colleague

That code still doesn't compile (which suggests that you're not showing me your actual code), and when I fix the syntax error on your fgets() call, it doesn't fault on my system.

Narue 5,707 Bad Cop Team Colleague

If someone could help me with the most efficient way, I would greatly appreciate it.

Your code is I/O bound, "efficient" shouldn't enter your vocabulary unless user testing shows perceived performance to be unacceptable. Though since you asked, I would prefer accepting a series of base/height pairs on the same line. That way you don't keep bugging the user with prompts:

string line;

if (getline(cin, line)) {
    stringstream sep(line);
    double base, height;

    while (sep >> base >> height)
        cout << "The area of the triangle is: " <<  height * base / 2 << '\n';
}
Narue 5,707 Bad Cop Team Colleague

Please post a complete main() function that exhibits the problem. The snippets you posted are clearly not the code you're trying to execute because they won't compile.

Narue 5,707 Bad Cop Team Colleague
dst = realloc(dst, ++n);

It should be this:

dst = realloc(dst, ++n * sizeof *dst);

And that, my friend, is proof that regardless of your experience or ability, stupid mistakes happen. Especially if you work with higher level language too often and then drop down to a low level language that doesn't hold your hand. ;)

Narue 5,707 Bad Cop Team Colleague

Your use of strtok() is correct. The problem is your use of the uninitialized argv. You need to make sure that all destination strings have been allocated sufficient memory. Compare and contrast:

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

char *copy_str(const char *s)
{
    char *copy = malloc(strlen(s) + 1);
    
    if (copy != NULL)
        strcpy(copy, s);
        
    return copy;
}

char **split_str(const char *s, const char *delim)
{
    /*
        Error handling omitted for brevity
    */
    char **dst = malloc(sizeof *dst);
    char *src = copy_str(s);
    char *tok = strtok(src, delim);
    size_t n = 0;
    
    while (tok != NULL) {
        dst = realloc(dst, ++n);
        dst[n - 1] = copy_str(tok);
        tok = strtok(NULL, delim);
    }
    
    dst[n] = NULL;    
    free(src);
    
    return dst;
}

int main(void)
{
    char **s = split_str("this|is|a|test", "|");
    size_t i;
    
    for (i = 0; s[i] != NULL; i++) {
        printf("'%s'\n", s[i]);
        free(s[i]);
    }
    
    free(s);
    
    return 0;
}