The "IT DOESN'T WORK!" thread

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

User avatar
ahammel
My Little Cabbage
Posts: 2126
Joined: Mon Jan 30, 2012 12:46 am UTC
Location: Vancouver BC
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby ahammel » Sat May 03, 2014 12:22 am UTC

Xeio wrote:
3rdtry wrote:(Still, it's 2014, why can't I return two or three objects directly? Parameters should always be inputs)

You can, just not in Java. C#, Python, Go, etc. can all do it.
Apparently you can do it in Java as well, it's just hideous. (Amusingly, the Java example appears to be the longest on that page).

Though you return an array of object if you really want.
To be fair, that's all you do in Python and C# and the like (Go and Common Lisp have "real" multiple return values).
He/Him/His/Alex
God damn these electric sex pants!

User avatar
chridd
Has a vermicelli title
Posts: 710
Joined: Tue Aug 19, 2008 10:07 am UTC
Location: ...Earth, I guess?
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby chridd » Sat May 03, 2014 2:44 am UTC

ahammel wrote:
Xeio wrote:
3rdtry wrote:(Still, it's 2014, why can't I return two or three objects directly? Parameters should always be inputs)

You can, just not in Java. C#, Python, Go, etc. can all do it.
Apparently you can do it in Java as well, it's just hideous. (Amusingly, the Java example appears to be the longest on that page).

Code: Select all

public class Main {
public static class FooReturn {
    public int someNumber;
    public String someString;
    public FooReturn(int n, String s) {someNumber = n; someString = s;}
}
public static FooReturn foo() {
    return new FooReturn(42, "hello");
}
public static void main(String[] args) {
    FooReturn r = foo();
    System.out.println(r.someNumber+", "+r.someString);
}
}
I don't know why the example that you just linked is so long. (Also, having multiple return values seems like it would be awkward in a longer expression.)
~ chri d. d. /tʃɹɪ.di.di/ (Phonotactics? What phonotactics?) · ze or they · Forum game scores
mittfh wrote:I wish this post was very quotable...
flicky1991 wrote:In both cases the quote is "I'm being quoted too much!"

User avatar
ahammel
My Little Cabbage
Posts: 2126
Joined: Mon Jan 30, 2012 12:46 am UTC
Location: Vancouver BC
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby ahammel » Sat May 03, 2014 3:01 am UTC

chridd wrote:I don't know why the example that you just linked is so long.

Eh, fair enough. Looking through the page, some of the other examples are pretty ridiculous (Erlang, for instance).
He/Him/His/Alex
God damn these electric sex pants!

User avatar
Xeio
Friends, Faidites, Countrymen
Posts: 5078
Joined: Wed Jul 25, 2007 11:12 am UTC
Location: C:\Users\Xeio\
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby Xeio » Sat May 03, 2014 3:44 am UTC

ahammel wrote:
Though you return an array of object if you really want.
To be fair, that's all you do in Python and C# and the like (Go and Common Lisp have "real" multiple return values).
Ew. No.

C# has out and ref keywords. You should not be using Tuples like that. Not that I've never done it like that, but the language supported way is better.

Python, being a bit more flexible, Tuples aren't quite as nasty, and are supported language side as in comma separated assignments.

I should update that Rosetta code entry, I've already written some others on there if I can remember my account info...

Edit: Nope, no idea what the hell I made my password in 2009 (my first edit) and I'm too lazy to make a new one. Oh well.

User avatar
Xenomortis
Not actually a special flower.
Posts: 1373
Joined: Thu Oct 11, 2012 8:47 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby Xenomortis » Sun May 04, 2014 4:56 pm UTC

I thought my code was going to stop after allocating a few megabytes.
My desktop had other ideas though, and is now ignoring all input as it tries to thrash its brains out.
Image

User avatar
Jplus
Posts: 1686
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

Re: The "IT DOESN'T WORK!" thread

Postby Jplus » Mon May 05, 2014 11:02 am UTC

ahammel wrote:
chridd wrote:I don't know why the example that you just linked is so long.

Eh, fair enough. Looking through the page, some of the other examples are pretty ridiculous (Erlang, for instance).

In both cases the Java "solution" is still hideous though. I mean, you have to write a new class for every function you want to return multiple values from.
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

User avatar
Xenomortis
Not actually a special flower.
Posts: 1373
Joined: Thu Oct 11, 2012 8:47 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby Xenomortis » Mon May 05, 2014 3:18 pm UTC

Code: Select all

error C2664: 'void (MyClassA *,MyClassA *,MyClassB *,std::unordered_map<_Kty,_Ty> *)' : cannot convert parameter 4 from 'std::unordered_map<_Kty,_Ty> *' to 'std::unordered_map<_Kty,_Ty> *'

Er... what?

(I tried passing std::unordered_map< V, K > as an argument to std::thread when it should have been std::unordered_map< K, V >).
Image

User avatar
Yakk
Poster with most posts but no title.
Posts: 11034
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: The "IT DOESN'T WORK!" thread

Postby Yakk » Mon May 05, 2014 3:37 pm UTC

The next few lines of the error will say what the _Kty and _Ty types are in the two cases.
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.

User avatar
snowyowl
Posts: 464
Joined: Tue Jun 23, 2009 7:36 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby snowyowl » Thu May 08, 2014 11:24 pm UTC

Code: Select all

Create Function getCodeAcronym(i_value mediumint)
returns char(30)
READS SQL DATA
begin
declare p_acronym char(30);

   SELECT Acronym into p_acronym FROM codes  WHERE id = i_value ;

   return(p_acronym);
   
End


I'm assured that "this works on my machine" by the guy who wrote it, but my own copy of MySQL cries syntax error on the first semicolon. As you might expect, I have an entire folder of SQL that works on his machine.
The preceding comment is an automated response.

Great Justice
Posts: 54
Joined: Sun Aug 15, 2010 5:28 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby Great Justice » Fri May 09, 2014 12:37 am UTC

You have to temporarily change the delimiter

Code: Select all

DELIMITER //
CREATE FUNCTION ...
...
RETURN d;
END;
//
DELIMITER ;
It usually isn't Congress or the State that tries to abridge free expression or free speech, [...] actually, in the present situation, the main threat to expression comes from public opinion.
~Christopher Hitchens

User avatar
snowyowl
Posts: 464
Joined: Tue Jun 23, 2009 7:36 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby snowyowl » Fri May 09, 2014 8:50 am UTC

Yep, that works.

The greater mystery is that this code is allegedly one of the setup scripts for our database, which has actually already been setup and works fine. Is there some weird configuration setting that would make this code runnable as written?

Another example:

Code: Select all

rem run all data load scripts

@"C:\Program Files\Apache Group\Apache2\htdocs\CFIDE\wwwroot\groupapp\sql\tables.sql"
@"C:\Program Files\Apache Group\Apache2\htdocs\CFIDE\wwwroot\groupapp\sql\load_codes.sql"
@"C:\Program Files\Apache Group\Apache2\htdocs\CFIDE\wwwroot\groupapp\sql\load_persons.sql"
@"C:\Program Files\Apache Group\Apache2\htdocs\CFIDE\wwwroot\groupapp\sql\load_groups.sql"
@"C:\Program Files\Apache Group\Apache2\htdocs\CFIDE\wwwroot\groupapp\sql\load_relations.sql"


Pretty obvious what the intent is, but it doesn't do anything. Am I correct in thinking "rem" doesn't mean anything in MySQL? What's actually going on here?
The preceding comment is an automated response.

User avatar
Jplus
Posts: 1686
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

Re: The "IT DOESN'T WORK!" thread

Postby Jplus » Fri May 09, 2014 11:29 am UTC

Looks like a Windows batch script comment line.
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

speising
Posts: 1899
Joined: Mon Sep 03, 2012 4:54 pm UTC
Location: wien

Re: The "IT DOESN'T WORK!" thread

Postby speising » Fri May 09, 2014 11:58 am UTC

the whole thing is a batch script (see the "@", which suppresses console echo), which only makes sense if sql files are associated with some executable which runs them. (on my system, they'd just open up in my editor)

User avatar
snowyowl
Posts: 464
Joined: Tue Jun 23, 2009 7:36 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby snowyowl » Fri May 09, 2014 1:34 pm UTC

And that's a *.sql file, not a *.bat, for some reason.

Thanks for the help.
The preceding comment is an automated response.

Rysto
Posts: 1458
Joined: Wed Mar 21, 2007 4:07 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby Rysto » Sat May 17, 2014 2:03 am UTC

Argh...

I started using somebody else's library for a new feature. It was very convenient and helped me solve some important problems easily, so that's good. Unfortunately, I'm using it in an environment where security is paramount, so I had to audit it for security problems. The pain never ends:

1) It can recurse indefinitely on untrusted input
2) In some other places, it very carefully tracks the current recursion level and *aborts* if it recurses too far.
3) Every single non-mutating operation on its data structures allocate memory (and then frees it again). In some cases, if the allocation fails it returns a potentially incorrect result. In the rest of the cases, it very carefully checks for a failed allocation and then explicitly aborts if the memory allocation failed.
4) It doesn't restrict the nesting level of recursive data structures. This interacts badly with #1 and #2, as an unwitting user of the library can legitimately create a data structure that nests too far and then blows up later on.

Oh, and not security related, but it also borrows the name of several symbols from a different library that provides similar functionality. I can't use this other library for licensing reasons, but there will be situations where my code links with code that uses the other library, causing symbol conflicts. Urge to kill rising...

User avatar
Xenomortis
Not actually a special flower.
Posts: 1373
Joined: Thu Oct 11, 2012 8:47 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby Xenomortis » Fri Jul 04, 2014 9:45 am UTC

Code: Select all

[me@mydesk ~]$ ssh othercomputer
[me@othercomputer ~]$ ./someprogram
Your program runs, all is well.

Walk to othercomputer (about 300m away)

Code: Select all

[someoneelse@othercomputer ~]$ su me
[me@othercomputer ~]$ ./someprogram
SADNESS
Image

User avatar
phlip
Restorer of Worlds
Posts: 7535
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby phlip » Fri Jul 04, 2014 2:31 pm UTC

Any difference if you "su - me"?

Code: Select all

enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}
[he/him/his]

User avatar
Xenomortis
Not actually a special flower.
Posts: 1373
Joined: Thu Oct 11, 2012 8:47 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby Xenomortis » Fri Jul 04, 2014 2:42 pm UTC

I don't recall trying it on the machine over there (someone suggested it yesterday, but I was at my desk, and it's a long walk to find out).

But being on the other computer and then using an ssh session to itself worked too.
Image

0xD34D
Posts: 6
Joined: Fri Jul 11, 2014 1:48 am UTC
Location: USA

Re: The "IT DOESN'T WORK!" thread

Postby 0xD34D » Fri Jul 11, 2014 1:52 am UTC

Alright, so I am having a problem with something surprisingly simple...I can't figure out how to calculate a fibonacci sequence in C. I have the following code, but it either segfaults or returns random values. I feel like an absolute moron for not being able to get this to work.

Code: Select all

/*uses a loop function to calculate the n-th fib num*/
#include <stdio.h>
int fib(int n);

int main(void) {
   int n, count, i = 0;
   printf("Enter a number.\n");
   scanf("%d", &n);
   printf("%d\n", fib(n));
   return 0;
}

int fib(int n) {
   if(n == 0) {
      return 0;
   } else if (n == 1) {
      return n
   } else {
      return (fib(n-1) + fib(n-2));
   }
}

User avatar
NecklaceOfShadow
Posts: 775
Joined: Sun May 03, 2009 7:40 pm UTC
Location: In the alchemical aether
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby NecklaceOfShadow » Fri Jul 11, 2014 1:08 pm UTC

It wouldn't compile for me because you're missing a semicolon in fib. Once I added the semicolon, it seemed to work correctly for me. Could you give a bit more detail about how it fails?
Significantly less weird than I used to be. Still pretty weird.

οὗτός ἐστιν Ἀγαμέμνων, ἐμὸς
πόσις, νεκρὸς δὲ τῆσδε δεξιᾶς χερός
ἔργον δικαίας τέκτονος. τάδ’ ὧδ’ ἔχει.

User avatar
Jplus
Posts: 1686
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

Re: The "IT DOESN'T WORK!" thread

Postby Jplus » Fri Jul 11, 2014 2:24 pm UTC

As an aside, that is not a loop function but a recursive function. Thought I should mention that.
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

0xD34D
Posts: 6
Joined: Fri Jul 11, 2014 1:48 am UTC
Location: USA

Re: The "IT DOESN'T WORK!" thread

Postby 0xD34D » Fri Jul 11, 2014 5:20 pm UTC

NecklaceOfShadow wrote:It wouldn't compile for me because you're missing a semicolon in fib. Once I added the semicolon, it seemed to work correctly for me. Could you give a bit more detail about how it fails?


Well, I'll try again with the semicolon that was apprently missing. I would type in a number [n] and it would just return [n]. No modification or anything.

Thanks for the help.

User avatar
PM 2Ring
Posts: 3613
Joined: Mon Jan 26, 2009 3:19 pm UTC
Location: Mid north coast, NSW, Australia

Re: The "IT DOESN'T WORK!" thread

Postby PM 2Ring » Sat Jul 12, 2014 1:01 pm UTC

Jplus wrote:As an aside, that is not a loop function but a recursive function. Thought I should mention that.

Indeed.

0xD34D, please try to do this using a simple loop. If you need help, feel free to ask here for hints.

Recursion can be useful, but a plain loop is generally more efficient. There are situations when the compiler can "magically" convert a single recursive call into a plain loop automatically, but that's not so easy for it to do when there's two recursive calls. The rule of thumb in C is to avoid recursion unless you really do need it, or it makes the code a whole lot more readable. (OTOH, in some weird languages, recursion is actually encouraged! :) )

Fancy
Posts: 57
Joined: Sun Jul 13, 2014 7:23 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby Fancy » Sun Jul 13, 2014 7:28 pm UTC

I'm working on learning C and the book has a problem "Design a function tooutput up to the nth character."

I've got the following code, but it just isn't working. First I had it returning nothing, now it returns the original string. Could someone pelase point out my error to me?

Code: Select all

#include <stdio.h>

void find_nth(char **str, int n);
int main(void) {
   int n;
   char str[101];
   char *ptr = str;
   puts("Enter a string:");
   fgets(str, 100, stdin);
   puts("How many characters would you like printed?");
   scanf("%d", &n);
   find_nth(&ptr, n);
   printf("Your string up to the %d char is %s\n", n, str);

   return 0;
}

void find_nth(char **str, int n) {
   int count;
   for(count = 0; count < n; count++) {
      *(str++);   
   }
   *(str + count + 1) = '\0';
}

User avatar
PM 2Ring
Posts: 3613
Joined: Mon Jan 26, 2009 3:19 pm UTC
Location: Mid north coast, NSW, Australia

Re: The "IT DOESN'T WORK!" thread

Postby PM 2Ring » Mon Jul 14, 2014 8:10 am UTC

Fancy,

Your code has several pointer-related problems. I'll give you a few hints that will hopefully help you to repair it.

• Change find_nth() to take a simple char pointer, e.g.,
void find_nth(char *str, int n)

char ** is a pointer to a pointer, which is useful when you have an array of strings, like char **argv, but that's not what you want here.
Actually, it'd be a Good Idea to make find_nth() return an error code if n is longer than the string length; you certainly don't want it to try to modify a char beyond the end of the array.

• Your main() function does weird things with ptr, but I guess that's a side-effect of your find_nth() taking a pointer to a pointer.

• The for loop in find_nth() increments both count and str, so (str + count + 1) doesn't point where you want it to.

The name of find_nth() is a bit misleading. I'd expect such a function to return an index or a pointer to the thing it found (or an error code if not found, or if called with a bad argument); I wouldn't expect it to modify the string I passed it. But that's a minor quibble.

If you need more hints, please ask.

Fancy
Posts: 57
Joined: Sun Jul 13, 2014 7:23 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby Fancy » Mon Jul 14, 2014 2:00 pm UTC

PM 2Ring wrote:Fancy,

Your code has several pointer-related problems. I'll give you a few hints that will hopefully help you to repair it.
• Your main() function does weird things with ptr, but I guess that's a side-effect of your find_nth() taking a pointer to a pointer.
If you need more hints, please ask.


I changed what I understood from your post, but am still a bit confused. What exactly is main doing with pointers that is weird? Also, the exact programming problem (followed by my updated attempt at coding it.)

Design and test a function that fetches the next n characters from input (including blanks, tabs, and newlines), storing the results in an array whose address is passed an argument.

Come to think of it, I think I might be going at this all wrong. Maybe a getchar() for count chars and then into an array would work better?

Code: Select all

#include <stdio.h>

void find_nth(char *str, int n);
int main(void) {
   int n;
   char str[101];
   char *ptr = str;
   puts("Enter a string:");
   fgets(str, 100, stdin);
   puts("How many characters would you like printed?");
   scanf("%d", &n);
   find_nth(&ptr, n);
   printf("Your string up to the %d char is %s\n", n, str);

   return 0;
}

void find_nth(char *str, int n) {
   int count;
   for(count = 0; count < n; count++)
       ; /*Intentional null statement, NOT an accident*/
   *(str + count + 1) = '\0';
}
With many little strokes a large tree is felled.
-Japanese Proverb

User avatar
Xenomortis
Not actually a special flower.
Posts: 1373
Joined: Thu Oct 11, 2012 8:47 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby Xenomortis » Mon Jul 14, 2014 2:20 pm UTC

Does that even compile?
find_nth takes parameters of type char* and int, but you're passing it char** and int.
If that does compile, then find_nth is not going to end up doing what you expect, since the pointer you've received isn't meaningful in that context.

Fancy wrote:What exactly is main doing with pointers that is weird?

Your original "find_nth" took a parameter of type char** - a pointer to a pointer to a char.
This wasn't what you really wanted.
It had the knock-on effect that main had to pass a pointer to ptr, instead of ptr itself (hence you're calling it with "find_nth( &ptr )"), which is unusual for the task at hand.

I'd really like a way to write inline code segments...

Fancy wrote:Come to think of it, I think I might be going at this all wrong. Maybe a getchar() for count chars and then into an array would work better?

Nah, this way is simpler.
Image

Fancy
Posts: 57
Joined: Sun Jul 13, 2014 7:23 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby Fancy » Mon Jul 14, 2014 2:40 pm UTC

Xenomortis wrote:Does that even compile?
find_nth takes parameters of type char* and int, but you're passing it char** and int.
If that does compile, then find_nth is not going to end up doing what you expect, since the pointer you've received isn't meaningful in that context.

Fancy wrote:What exactly is main doing with pointers that is weird?

Your original "find_nth" took a parameter of type char** - a pointer to a pointer to a char.
This wasn't what you really wanted.
It had the knock-on effect that main had to pass a pointer to ptr, instead of ptr itself (hence you're calling it with "find_nth( &ptr )"), which is unusual for the task at hand.

I'd really like a way to write inline code segments...

Fancy wrote:Come to think of it, I think I might be going at this all wrong. Maybe a getchar() for count chars and then into an array would work better?

Nah, this way is simpler.


It does compile, and I have it down to no warnings or anything, but it just prints the entire original string regardless.

EDIT
Probably because I'm an idiot. I made a second string to store the characters that are requested (probably not the best way, but whatever) and then forgot to change my printf to print the new string. Thanks for the help.
With many little strokes a large tree is felled.
-Japanese Proverb

User avatar
Xenomortis
Not actually a special flower.
Posts: 1373
Joined: Thu Oct 11, 2012 8:47 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby Xenomortis » Mon Jul 14, 2014 3:00 pm UTC

Fancy wrote:It does compile, and I have down to no warnings or anything, but it just prints the entire original string regardless.

Are you absolutely sure that this:
Spoiler:

Code: Select all

#include <stdio.h>

void find_nth(char *str, int n);
int main(void) {
   int n;
   char str[101];
   char *ptr = str;
   puts("Enter a string:");
   fgets(str, 100, stdin);
   puts("How many characters would you like printed?");
   scanf("%d", &n);
   find_nth(&ptr, n);
   printf("Your string up to the %d char is %s\n", n, str);

   return 0;
}

void find_nth(char *str, int n) {
   int count;
   for(count = 0; count < n; count++)
       ; /*Intentional null statement, NOT an accident*/
   *(str + count + 1) = '\0';
}

That is, the second code block you've posted, compiles with no warnings?
Here's a warning from gcc:

Code: Select all

test.c: In function ‘main’:
test.c:12: warning: passing argument 1 of ‘find_nth’ from incompatible pointer type
test.c:3: note: expected ‘char *’ but argument is of type ‘char **’

Obviously C is somewhat forgiving with mis-matched types.

Point is, this code fails because find_nth is doing stuff with a meaningless pointer (it's not changing the string because you've not passed it a pointer to your string, but a pointer to somewhere "random" (although I can make a pretty good guess where that pointer is pointing to)).

Fancy wrote:Porbably because I'm an idiot. I made a second string to store the characters that are requested (probably not the best way, but whatever) and then forgot to change my printf to print the new string. Thanks for the help.

No.
Your code stores precisely one string. You do not copy it anywhere.

Edit:
As I've hinted at twice, there is a single character in your code that's causing it to fail.
Image

Fancy
Posts: 57
Joined: Sun Jul 13, 2014 7:23 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby Fancy » Mon Jul 14, 2014 3:27 pm UTC

Xenomortis wrote:
Fancy wrote:It does compile, and I have down to no warnings or anything, but it just prints the entire original string regardless.

Are you absolutely sure that this:
Spoiler:

Code: Select all

#include <stdio.h>

void find_nth(char *str, int n);
int main(void) {
   int n;
   char str[101];
   char *ptr = str;
   puts("Enter a string:");
   fgets(str, 100, stdin);
   puts("How many characters would you like printed?");
   scanf("%d", &n);
   find_nth(&ptr, n);
   printf("Your string up to the %d char is %s\n", n, str);

   return 0;
}

void find_nth(char *str, int n) {
   int count;
   for(count = 0; count < n; count++)
       ; /*Intentional null statement, NOT an accident*/
   *(str + count + 1) = '\0';
}

That is, the second code block you've posted, compiles with no warnings?
Here's a warning from gcc:

Code: Select all

test.c: In function ‘main’:
test.c:12: warning: passing argument 1 of ‘find_nth’ from incompatible pointer type
test.c:3: note: expected ‘char *’ but argument is of type ‘char **’

Obviously C is somewhat forgiving with mis-matched types.

Point is, this code fails because find_nth is doing stuff with a meaningless pointer (it's not changing the string because you've not passed it a pointer to your string, but a pointer to somewhere "random" (although I can make a pretty good guess where that pointer is pointing to)).

Fancy wrote:Porbably because I'm an idiot. I made a second string to store the characters that are requested (probably not the best way, but whatever) and then forgot to change my printf to print the new string. Thanks for the help.

No.
Your code stores precisely one string. You do not copy it anywhere.

Edit:
As I've hinted at twice, there is a single character in your code that's causing it to fail.

Now it has a second string.
With many little strokes a large tree is felled.
-Japanese Proverb

User avatar
Xenomortis
Not actually a special flower.
Posts: 1373
Joined: Thu Oct 11, 2012 8:47 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby Xenomortis » Mon Jul 14, 2014 3:29 pm UTC

If it's working, great.
But do you understand why the code I was looking at was failing?
Image

Fancy
Posts: 57
Joined: Sun Jul 13, 2014 7:23 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby Fancy » Mon Jul 14, 2014 3:39 pm UTC

Xenomortis wrote:If it's working, great.
But do you understand why the code I was looking at was failing?


Because

Code: Select all

 **ch     points to an array of arrays (posssibly an array of strings
*ch points to just the single array, or int my case string
With many little strokes a large tree is felled.
-Japanese Proverb

Fancy
Posts: 57
Joined: Sun Jul 13, 2014 7:23 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby Fancy » Mon Jul 14, 2014 4:05 pm UTC

Xenomortis wrote:If it's working, great.
But do you understand why the code I was looking at was failing?


Because

Code: Select all

**ch     points to an array of arrays (posssibly an array of strings
*ch points to just the single array, or in my case a string
With many little strokes a large tree is felled.
-Japanese Proverb

User avatar
chridd
Has a vermicelli title
Posts: 710
Joined: Tue Aug 19, 2008 10:07 am UTC
Location: ...Earth, I guess?
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby chridd » Mon Jul 14, 2014 4:21 pm UTC

Fancy wrote:Also, the exact programming problem (followed by my updated attempt at coding it.)

Design and test a function that fetches the next n characters from input (including blanks, tabs, and newlines), storing the results in an array whose address is passed an argument.
Doesn't this mean that the function should be doing the input, rather than working with input that the program has already read? It sounds to me like they want you to make a function that does the same thing fgets does.
~ chri d. d. /tʃɹɪ.di.di/ (Phonotactics? What phonotactics?) · ze or they · Forum game scores
mittfh wrote:I wish this post was very quotable...
flicky1991 wrote:In both cases the quote is "I'm being quoted too much!"

User avatar
PM 2Ring
Posts: 3613
Joined: Mon Jan 26, 2009 3:19 pm UTC
Location: Mid north coast, NSW, Australia

Re: The "IT DOESN'T WORK!" thread

Postby PM 2Ring » Tue Jul 15, 2014 2:08 pm UTC

PM 2Ring wrote:Fancy,

Your code has several pointer-related problems. I'll give you a few hints that will hopefully help you to repair it.
• Your main() function does weird things with ptr, but I guess that's a side-effect of your find_nth() taking a pointer to a pointer.
If you need more hints, please ask.


Fancy wrote:I changed what I understood from your post, but am still a bit confused. What exactly is main doing with pointers that is weird?


I guess I should've been a bit more explicit. When I told you to "Change find_nth() to take a simple char pointer" I expected you to also change the call to find_nth() in main() to pass a plain pointer to char, not a double pointer. From the other thread, I assume you understand that in C the name of an array is a (constant) pointer to the first element of the array, so given
char str[101];
f(str) passes the address of the first char in str to f().

char *ptr = str;
creates space on the stack for a pointer, and stores in it the address of the first char in str.
To illustrate, let's say str[101] occupies bytes 1000 to 1100 in RAM and ptr occupies bytes 996 to 999 (it's a 32 bit system, I'm using decimal, and just making address numbers up).
So after you say
char *ptr = str;
then bytes 996 to 999 ( considered as a 32 bit number) contain the value 1000.
And if you say f(ptr) or f(str), then f receives 1000 as its argument.
But if you say f(&ptr), then f receives the address of ptr itself, which is 996. A small but highly significant difference!

As others have said, your compiler should warn you if you try to call a function with the wrong type of pointer. It's a Good Idea to set your compiler's warning level up high; eg, on gcc that's -Wall . There are even more extreme settings, but -Wall is generally adequate, IMHO, (but if someone wants to disagree, please feel free).


Fancy wrote:Also, the exact programming problem (followed by my updated attempt at coding it.)

Design and test a function that fetches the next n characters from input (including blanks, tabs, and newlines), storing the results in an array whose address is passed an argument.

Come to think of it, I think I might be going at this all wrong. Maybe a getchar() for count chars and then into an array would work better?


Yes, using getchar() is probably a good idea. fgets() is NOT really adequate for this task: it's for reading lines of text, so it stops reading chars when it sees a newline (or end of file). So you want a loop that reads chars using getchar() which exits when it gets the desired count number of chars or if EOF is reached. And don't forget to make sure that count isn't too big for your array.

Fancy wrote:

Code: Select all

#include <stdio.h>

void find_nth(char *str, int n);
int main(void) {
   int n;
   char str[101];
   char *ptr = str;
   puts("Enter a string:");
   fgets(str, 100, stdin);
   puts("How many characters would you like printed?");
   scanf("%d", &n);
   find_nth(&ptr, n);
   printf("Your string up to the %d char is %s\n", n, str);

   return 0;
}

void find_nth(char *str, int n) {
   int count;
   for(count = 0; count < n; count++)
       ; /*Intentional null statement, NOT an accident*/
   *(str + count + 1) = '\0';
}


FWIW, the loop

Code: Select all

   for(count = 0; count < n; count++)
       ; /*Intentional null statement, NOT an accident*/

Is a bit silly, it accomplishes the same thing as
count = n;

Anyway, it's getting rather late here, so I'd better go and get some sleeep. :)

User avatar
Xenomortis
Not actually a special flower.
Posts: 1373
Joined: Thu Oct 11, 2012 8:47 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby Xenomortis » Sun Jul 27, 2014 8:33 pm UTC

Network cards are the new printers.
My desktop has two of them and neither one is capable of maintaining a connection with a router 20 feet away.

Laptop's fine though; so now I'm in what feels like a perverse situation where my desktop is being fed internet by my laptop.
Image

User avatar
phlip
Restorer of Worlds
Posts: 7535
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

Re: The "IT DOESN'T WORK!" thread

Postby phlip » Mon Jul 28, 2014 12:21 am UTC

Xenomortis wrote:Network cards are the new printers.

Maybe your network card's WiFi cartridge has run out? Have to buy a new one for about $50 or so, should last you another few weeks.

Code: Select all

enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}
[he/him/his]

KnightExemplar
Posts: 5203
Joined: Sun Dec 26, 2010 1:58 pm UTC

Re: The "IT DOESN'T WORK!" thread

Postby KnightExemplar » Tue Aug 19, 2014 1:43 pm UTC

Xenomortis wrote:Network cards are the new printers.
My desktop has two of them and neither one is capable of maintaining a connection with a router 20 feet away.

Laptop's fine though; so now I'm in what feels like a perverse situation where my desktop is being fed internet by my laptop.


Routers are the new printers.

Buy a decent router, and many network cards will work. Stick with free-Verizon crap routers, and I've noticed that all Realtek Wi-Fi cards / dongles fail with them.

I have no idea why the free-Verizon crap router fails to work with Realtek chips, but its the truth. Realtek is an extremely common wifi chip however. I've fixed the problem by getting a decent router.
First Strike +1/+1 and Indestructible.

User avatar
Xenomortis
Not actually a special flower.
Posts: 1373
Joined: Thu Oct 11, 2012 8:47 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby Xenomortis » Tue Aug 19, 2014 1:52 pm UTC

I believe it's the standard router BT give you.
It's more stable now (not dependent on laptop).

Never had a problem with the BT routers we had at my last home (which we used for years).
Image

Rysto
Posts: 1458
Joined: Wed Mar 21, 2007 4:07 am UTC

Re: The "IT DOESN'T WORK!" thread

Postby Rysto » Sat Aug 30, 2014 11:57 pm UTC

I'm working on making our code base at work compile with a newer version of gcc and a new version of the OS. Of course this means that I get to find all of the moronic things that people have done in our code. I've just wasted an hour trying to track down the source of this:

Code: Select all

c++/4.9.0/bits/stl_multiset.h:426:17: error: operator '>=' has no left operand
 #if __cplusplus >= 201103L

I spent forever playing with compiler flags before I finally got enough sense to check whether the source file was doing something ridiculous. Of course, it was:

Spoiler:

Code: Select all

#undef __cplusplus
So much rage...


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 3 guests