Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Avenging Dentist posted:

Python is strongly typed. The word you're looking for is "statically".

God I hate the strong and weak type terminology. It's pretty useless since most languages are strongly typed anyways.

Adbot
ADBOT LOVES YOU

PAH-PAH POKER FACE
Nov 7, 2009
What are the best books to learn PHP and Javascript?

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

MEAT TREAT posted:

God I hate the strong and weak type terminology. It's pretty useless since most languages are strongly typed anyways.

Perl, and to some degree, C and C++ are weakly typed.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Javascript is too I think, but I just don't like the term because like you said C and C++ could both be considered weakly typed.

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender

MEAT TREAT posted:

Javascript is too I think, but I just don't like the term because like you said C and C++ could both be considered weakly typed.

To be fair, it's an important distinction in type theory. If it makes you feel better, you can use the slightly more formal terms:

Instead of "dynamic typing", say the language has "value typing" - types are attached to individual values at runtime.
Instead of "static typing", say the language has "name typing" - types are attached to names and variables at compile time.
Instead of "weak typing", say the language has "implicit type conversions" - expressions of a certain type may be used as if they had a different type, and the compiler will silently convert.
Instead of "strong typing", say the language has "explicit type conversions" or "no type conversions" - types are immutable, and must be converted by the programmer's direction.

"Weak typing" is a popular term because most people working in type theory want to avoid programmer errors as one of the most important reasons for their work; "if it compiles, then it will work" is a major goal in the field. Implicit conversions are seen as one of the most damaging ways to undermine this goal, as trivial programmer mistakes are silently allowed by the compiler with potentially large effects on the behavior of the program and hard-to-track-down bugs.

There are other important axis of type systems: "polymorphic types", "subtypes (nominal/structural/neither/both)", "first-class functions", "higher-order types (none/second-order/nth-order)", "dependent types (none/subturing/turing)", "type families", and more. Some of these are more general than others; certainly a language with dependent types can implement any other type system, for example, but very few people support real-world programming with dependent types outside academia and life-critical system design.

Unfortunately, many -- perhaps even most -- languages are difficult to classify without more precision. Perl, for example, has static typing for the base types (you can determine statically if something is a scalar, hash, or array because they use different sigils) but dynamic typing for references (and consequently objects and just about all interesting data structures) so we usually consider it a dynamic language. C and C++ have static typing and an exciting helping of implicit conversions. Most statically typed languages have some sort of wrapper that can hold dynamically-typed values; every object-oriented language has such wrappers for at least some kind of subset types, as the entire point of object-oriented programming is dynamic dispatch via virtual method calls. Some type systems are stronger than others; for example, Perl doesn't even make any distinction whatsoever between a number and a string, C has separate string, integer, float, etc. but allows implicit conversions between different numeric types, and Haskell lets you go crazy and define type restrictions that enforce the units of measurement on your numeric expressions if you want. POSIX shell only has values of a single type; it is trivially statically and strongly typed, but that's not an interesting statement.

RussianManiac
Dec 27, 2005

by Ozmaugh

PAH-PAH POKER FACE posted:

What are the best books to learn PHP and Javascript?

Don't get books. Just think of a somewhat challenging project to do with either one of them and learn on the way from internet reference/tutorials. At least that is the way I learn best. Reading a big book doesn't seem to do the trick, the best way is to actually do stuff and learn on the way.

On that note php.net has almost everything you want about php.

Blotto Skorzany
Nov 7, 2008

He's a PSoC, loose and runnin'
came the whisper from each lip
And he's here to do some business with
the bad ADC on his chip
bad ADC on his chiiiiip

RussianManiac posted:

Don't get books. Just think of a somewhat challenging project to do with either one of them and learn on the way from internet reference/tutorials. At least that is the way I learn best. Reading a big book doesn't seem to do the trick, the best way is to actually do stuff and learn on the way.

On that note php.net has almost everything you want about php.


In a word, no. There are many, many bad php tutorials and references on the web. Some of them are even on php.net! As a rule, don't consult php.net for anything other than function arguments and syntax questions. Don't consult any other online php poo poo at all until you understand every step of how php's 'best practices' for prevent sql injection went from addslashes -> magic_quotes -> mysql_escape_string -> mysql_real_escape_string -> mysqli::prepare/mysqli::bind_params . In general, if you want to learn to write good PHP, learn some other language and web framework and translate your work to PHP. The PHP culture is toxic.

For javascript, there are a number of decent jquery intros, and the basics of the language and its stdlib are simple enough to google for

tef
May 30, 2004

-> some l-system crap ->

PAH-PAH POKER FACE posted:

What are the best books to learn PHP and Javascript?

java script: The good parts, by Douglas Crockford is a short and succinct guide to the better parts of the language.

raminasi
Jan 25, 2005

a last drink with no ice

RussianManiac posted:

Don't get books. Just think of a somewhat challenging project to do with either one of them and learn on the way from internet reference/tutorials. At least that is the way I learn best. Reading a big book doesn't seem to do the trick, the best way is to actually do stuff and learn on the way.

On that note php.net has almost everything you want about php.

I can think of no two worse languages to try to learn from only web tutorials than Javascript and PHP.

zootm
Aug 8, 2006

We used to be better friends.
Anal-retentive post time.

ShoulderDaemon posted:

Instead of "dynamic typing", say the language has "value typing" - types are attached to individual values at runtime.
I think that "dynamic typing" is actually correct here; I've not heard of "value typing", but "dynamic" (or sometimes "latent") is the term you see in use. It's not ambiguous. "Typing" is a bit confusing, as is pointed out in Types and Programming Languages:

quote:

Terms like "dynamically typed" are arguably misnomers and should probably be replaced by "dynamically checked," but the usage is standard.
As alluded to here, "dynamically checked" is probably the best choice of words if you want to avoid ambiguity here.

ShoulderDaemon posted:

Instead of "static typing", say the language has "name typing" - types are attached to names and variables at compile time.
Name typing is probably a bad name to use, because it's easily confused with "nominal types", one of the means of defining type systems. It's more common in languages that are actually in common use, but "structural types" (where one only needs to have the correct type signature in order to be considered a subtype) are more popular in academic languages. Again, I think that "static" is pretty standard and unambiguous, although "statically checked" might be a better way of putting it.

ShoulderDaemon posted:

Instead of "weak typing", say the language has "implicit type conversions" - expressions of a certain type may be used as if they had a different type, and the compiler will silently convert.
The important thing about this is that "weak" is an ambiguous term. The other thing that people sometimes mean when they refer to "weak" type systems is actual untyped systems, where the system will blindly use the value they are given as though it had the memory structure of the type they were expecting, whether or not that is the case. This is the case with C (albeit not always) and assembly-level languages. Where it's accompanied with some checking (as in C), the term used tends to be "unsafe", to contrast with dynamically- or statically-typed languages which will always (regardless of their checking scheme) detect a type error either at run- or compile-time. When it's not, I think that "untyped" probably applies.

ShoulderDaemon" posted:

Instead of "strong typing", say the language has "explicit type conversions" or "no type conversions" - types are immutable, and must be converted by the programmer's direction.
I think given the other terms mentioned here, the term "strong" really should not be used at all. In particular there are languages with implicit type conversions which are as "strongly" typed as any other language - in particular Scala has a whole implicit type conversion mechanism that is programmer-controlled, but is as statically checked and safe as it would be without it.

I don't intend to be picky, I just don't want bad terms replaced with more rarely-used or unusual terms. Your post is an excellent description of the difficulties in classifying type systems.

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender

zootm posted:

I've not heard of "value typing", [...] Name typing is probably a bad name to use, because it's easily confused with "nominal types", one of the means of defining type systems.

That's fair; I mostly see the terms in the works of mathematicians rather than computer scientists, describing the model checkers they've built for some logic language. For anyone working in CS I suppose sticking with the established names will avoid confusion.

zootm
Aug 8, 2006

We used to be better friends.

ShoulderDaemon posted:

That's fair; I mostly see the terms in the works of mathematicians rather than computer scientists, describing the model checkers they've built for some logic language. For anyone working in CS I suppose sticking with the established names will avoid confusion.
That makes sense, yeah. I think those terms make more sense outside of the world of programming languages and and their runtimes.

Fly
Nov 3, 2002

moral compass

zootm posted:

That makes sense, yeah. I think those terms make more sense outside of the world of programming languages and and their runtimes.
I agree that using the correct names is best, but your alternate names are good for exposition. :)

Danger Mahoney
Mar 19, 2007

by FactsAreUseless
I have a super-quick question: I stumbled across an ebook the other day that was aimed at teaching people basic Python by creating a simple game from the ground up (I think using pygame). It could be viewed as a PDF or regular HTML, and its 'cover' had a old-timey illustration of a dude fighting a dragon with code overlaid on some parts.

Anyone know what I'm talking about or where I could find it again?

mellowjournalism
Jul 31, 2004

helllooo
Anyone know of a way I can remotely deploy Windows Services to a cluster of machines from one machine? Any way this can be done quickly so when testing a new build I can just compile, remote install, and debug all from one machine?

pliable
Sep 26, 2003

this is what u get for "180 x 180 avatars"

this is what u fucking get u bithc
Fun Shoe
I need help configuring build paths for Java in eclipse. My basic problem here is that I'm supposed to use a previous class that I wrote (in the picture, it's AStack.class under the Lab5 folder), and I'm not supposed to copy and make a new class for it. Instead, I have to configure the build path to use that class. I've managed to configure it to this point:



But now, how the hell do I actually use it in my StringChecker class file? I'm assuming I have to import it, but how? I tried "import AStack;", but that doesn't work. Any help is appreciated, thanks!

The B Man
Mar 21, 2007
'Cause life's too short to play Freebird

pliable posted:

I need help configuring build paths for Java in eclipse. My basic problem here is that I'm supposed to use a previous class that I wrote (in the picture, it's AStack.class under the Lab5 folder), and I'm not supposed to copy and make a new class for it. Instead, I have to configure the build path to use that class. I've managed to configure it to this point:



But now, how the hell do I actually use it in my StringChecker class file? I'm assuming I have to import it, but how? I tried "import AStack;", but that doesn't work. Any help is appreciated, thanks!

Imports are for classes in different packages to the current class. Because these are both in the default class you don't need to import it.

pliable
Sep 26, 2003

this is what u get for "180 x 180 avatars"

this is what u fucking get u bithc
Fun Shoe

The B Man posted:

Imports are for classes in different packages to the current class. Because these are both in the default class you don't need to import it.

Haha, yeah I kind of discovered that after just trying to use my AStack class. However, I didn't exactly know why, so that explains it. Thank you much!

Opinion Haver
Apr 9, 2007

I'm writing a small mail-checker program that polls an IMAP server every 20 seconds or whatever to see if you have new mail, leaving the imap connection open between requests to cut down on latency; occasionally, the program will throw this error (at least, when using it to check Gmail; I don't know about other IMAP servers):
code:
Traceback (most recent call last):
  File "XXXXXX", line 52, in <module>
    msgs = servers[server].check()
  File "XXXXXX", line 48, in check
    for folder in self.get_folders():
  File "XXXXXX", line 39, in get_folders
    for f_str in self.imap.list()[1]]
  File "/usr/lib/python2.5/imaplib.py", line 488, in list
    typ, dat = self._simple_command(name, directory, pattern)
  File "/usr/lib/python2.5/imaplib.py", line 1055, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "/usr/lib/python2.5/imaplib.py", line 885, in _command_complete
    typ, data = self._get_tagged_response(tag)
  File "/usr/lib/python2.5/imaplib.py", line 986, in _get_tagged_response
    self._get_response()
  File "/usr/lib/python2.5/imaplib.py", line 903, in _get_response
    resp = self._get_line()
  File "/usr/lib/python2.5/imaplib.py", line 996, in _get_line
    line = self.readline()
  File "/usr/lib/python2.5/imaplib.py", line 1162, in readline
    char = self.sslobj.read(1)
socket.sslerror: (8, 'EOF occurred in violation of protocol')
I don't know what's going on; I'm just using the standard imaplib interface and not messing with any kind of internals. I can't figure out any pattern as to when this happens or why. Any clue?

e: I posted this here because I'm wondering if Gmail closes connections that are held open for more than a specific length of time, or if I'm doing something else fundamentally wrong.

Opinion Haver fucked around with this message at 02:29 on Jan 24, 2010

Jonnty
Aug 2, 2007

The enemy has become a flaming star!

yaoi prophet posted:

I'm writing a small mail-checker program that polls an IMAP server every 20 seconds or whatever to see if you have new mail, leaving the imap connection open between requests to cut down on latency; occasionally, the program will throw this error (at least, when using it to check Gmail; I don't know about other IMAP servers):
code:
Traceback (most recent call last):
  File "XXXXXX", line 52, in <module>
    msgs = servers[server].check()
  File "XXXXXX", line 48, in check
    for folder in self.get_folders():
  File "XXXXXX", line 39, in get_folders
    for f_str in self.imap.list()[1]]
  File "/usr/lib/python2.5/imaplib.py", line 488, in list
    typ, dat = self._simple_command(name, directory, pattern)
  File "/usr/lib/python2.5/imaplib.py", line 1055, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "/usr/lib/python2.5/imaplib.py", line 885, in _command_complete
    typ, data = self._get_tagged_response(tag)
  File "/usr/lib/python2.5/imaplib.py", line 986, in _get_tagged_response
    self._get_response()
  File "/usr/lib/python2.5/imaplib.py", line 903, in _get_response
    resp = self._get_line()
  File "/usr/lib/python2.5/imaplib.py", line 996, in _get_line
    line = self.readline()
  File "/usr/lib/python2.5/imaplib.py", line 1162, in readline
    char = self.sslobj.read(1)
socket.sslerror: (8, 'EOF occurred in violation of protocol')
I don't know what's going on; I'm just using the standard imaplib interface and not messing with any kind of internals. I can't figure out any pattern as to when this happens or why. Any clue?

e: I posted this here because I'm wondering if Gmail closes connections that are held open for more than a specific length of time, or if I'm doing something else fundamentally wrong.

In all cases like this, you should google the interesting part of the error - in this case, the last line. It seems like a lot of people have had similar problems with the SSL library, which might shed some light on the issue you're having.

DrBouvenstein
Feb 28, 2007

I think I'm a doctor, but that doesn't make me a doctor. This fancy avatar does.
So I'm only a week in, and I've already regretted signing up for an online MATLAB course. I'd drop it if not for the fact that I'm an engineer, so I should know MATLAB, and I already dropped $100 on the software.

Yeah, it shouldn't be hard (especially since this is the first freakin' assignment...) but I can't figure this question out.

quote:

If x and y are matrices, where x = [1 2 3; 4 5 6; 7 8 9] and y = [1 2; 3 4 ; 5 6]. Complete the
following:
a. Let z be the product of x and y
b. Let w be the product of row 1 of x by column 2 of y (hint: use the colon operator)

Part a I did no problem, but part b has me going :confused:

So at first I just tried:
code:
w = x(1, :) * y(:, 2)
But that just gave me 28 (it multiplied the right indices together, but also added them all together...drat.)

Ok, so I tried using the .* command:
code:
w = x(1,:) .* y(:,2)
but that gave me an error

quote:

??? Error using ==> times
Matrix dimensions must agree.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Multiplying a row vector by a column vector is supposed to give you a scalar (or a 1x1 matrix, depending on how you think of it). If you want a component-wise product (and you probably don't!), you'll have to transpose one of the operands before using .* .

DrBouvenstein
Feb 28, 2007

I think I'm a doctor, but that doesn't make me a doctor. This fancy avatar does.
So...you're saying that 28 is probably the answer I'm looking for? And if for some reason she wants it to still be a vector, I have to use the ' command to transpose them and then go from there? Cause yeah, that does seem like a lot more steps then what I think te question is asking for...maybe...

Dijkstracula
Mar 18, 2003

You can't spell 'vector field' without me, Professor!

I think you need to revisit the definition of matrix multiplication, and then just work out the inner product by hand to convince yourself that you're doing it right. (you wonder about transposing the column vector; is the multiplication even defined if you do that?)

Also, now would be a good time to nail down that even a "scalar" in Matlab is a matrix, as stated above.

code:
>> size(3)

ans =

     1     1

Dijkstracula fucked around with this message at 01:44 on Jan 25, 2010

BigRedDot
Mar 6, 2008

Dijkstracula posted:

(you wonder about transposing the column vector; is the multiplication even defined if you do that?)
Depends on what you mean by multiplication. You could take the exterior product and produce a bivector. I'm goning to go out on a limb and guess that's not what is wanted.

Dijkstracula
Mar 18, 2003

You can't spell 'vector field' without me, Professor!

BigRedDot posted:

Depends on what you mean by multiplication. You could take the exterior product and produce a bivector. I'm goning to go out on a limb and guess that's not what is wanted.
Oh, indeed, but given that the prof deliberately chose a row and column vector, I'm pretty sure that the dot product was implied :)

Sweeper
Nov 29, 2007
The Joe Buck of Posting
Dinosaur Gum
Say I have two computers next to each other. I have a client running on one and a server running on another. I want the client to display data from the server, is it possible to do this over usb? Am I pretty much stuck using the network for this type of thing? No serial cable is possible since the other computer is a laptop.

pseudorandom name
May 6, 2007

Sweeper posted:

Say I have two computers next to each other. I have a client running on one and a server running on another. I want the client to display data from the server, is it possible to do this over usb? Am I pretty much stuck using the network for this type of thing? No serial cable is possible since the other computer is a laptop.

Buy a USB-to-serial adapter.

Sweeper
Nov 29, 2007
The Joe Buck of Posting
Dinosaur Gum

pseudorandom name posted:

Buy a USB-to-serial adapter.
Would it work just like a serial port then?

NiteFly
Feb 19, 2006

The Norse God of Fucking Metal!
The first post of this thread didn't mention a bash scripting megathread, so if there is a better place to ask this let me know.

I want to reference a variable indirectly. Pretty straight-forward for a name stored in a variable:
code:
value_i_want=some_value
variable_name=value_i_want
echo ${!variable_name} #Should print "some_value"
Does anyone know the syntax for doing this with a value stored in an array:
code:
values_i_want[0]=some_value
values_i_want[1]=some_other_value
variable_name=values_i_want
echo ${!variable_name[0]}
echo ${!variable_name[1]} #doesn't work, I want "some_other_value"
This doesn't even look like it should work to me, but I'm not familiar enough with bash to know how to approach this.

Any help is appreciated.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



NiteFly posted:

The first post of this thread didn't mention a bash scripting megathread, so if there is a better place to ask this let me know.

I want to reference a variable indirectly. Pretty straight-forward for a name stored in a variable:
code:
value_i_want=some_value
variable_name=value_i_want
echo ${!variable_name} #Should print "some_value"
Does anyone know the syntax for doing this with a value stored in an array:
code:
values_i_want[0]=some_value
values_i_want[1]=some_other_value
variable_name=values_i_want
echo ${!variable_name[0]}
echo ${!variable_name[1]} #doesn't work, I want "some_other_value"
This doesn't even look like it should work to me, but I'm not familiar enough with bash to know how to approach this.

Any help is appreciated.

http://tldp.org/LDP/abs/html/arrays.html says you should do this:
code:
# Copying an array.
array2=( "${array1[@]}" )
# or
array2="${array1[@]}"
but that won't work for sparse arrays, so scroll on down to example 26-9 for something that apparently will.

NiteFly
Feb 19, 2006

The Norse God of Fucking Metal!
Thanks for the reference. I had looked there before, but apparently glanced over what I needed.

PDP-1
Oct 12, 2004

It's a beautiful day in the neighborhood.

Sweeper posted:

Would it work just like a serial port then?

Ideally, yes. The adapter usually comes with a driver that emulates a serial port. In your program you connect to that fake port to communicate with that other machine.

You will probably need a null modem adapter in addition to your serial cable. Each computer will be trying to send data on pin 2 of the serial connector and will listen for data on pin 3. If you connect the computers with a straight pin-to-pin cable pin 2 will have two talkers and pin 3 will have two listeners and no data will get through. The null modem adapter swaps these two pins so that talker A is connected to listener B and vice-versa. Radio Shack has these parts for like $5.

If you are on a Windows machine look for a program called Hyperterminal inside your Accessories->Communications folder. Its a utility program for communicating over the serial ports and if you run it on both machines you can verify that everything is running well before introducing the extra variable of your own untested code.

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!
I was wondering about the inputs and outputs from a fast fourier transformation. I'm trying to jump back into this stuff after a half-assed 1-week education in frequency domain in college and some filter stuff I did in high school, so I'm a bit lost.

I'm following this text somewhat:
http://www.dspguide.com/ch12/3.htm

I wanted to pass in a wave, crunch it up into the frequency domain, and then use the some of the those waves to extrapolate what the wave might do. Overall it may or may not work but I thought I'd give it a try.

I'm trying to sort out the real and imaginary parts of the inputs and outputs. For example, I don't see myself having an imaginary component to my input; should I just assume my time-domain wave is fully represented in the real component and use zeroes for imaginary?

After that, I'm not sure what to do with the imaginary component from the frequency domain. I roughly recall there was magnitude and phase, and that phase would be the imaginary component. But I don't know what to do with it. So given, say, 32 points that I crunch with an FFT, I get 32 outputs. What does one pairing of that output represent and how could I manually represent it with trigonometric functions?

I know about the inverse transform but I don't know how to use it to extrapolate, so that's why I'm wanting to reconstruct the wave and extrapolate by summing the waves. Could I instead extend the output to, say, 64 values with zeroes on the latter 32 values, and would that basically extrapolate?

PDP-1
Oct 12, 2004

It's a beautiful day in the neighborhood.

Rocko Bonaparte posted:

Fourier transform stuff

If I understand you right what you want to do is sample some signal x(t) for T seconds, take the Fourier transform, and then use that result to estimate what the signal will be doing at some point in the near future.

The problem here is that when you try to reconstruct your input function from the inverse transform the result you get is going to be a new function that is periodic in T. For example if you sample x(t) for one second (T=1) and do the transform/inverse-transform to try to calculate what the system will be doing at t=1.1 seconds, what is really going to happen is that your function will 'loop around' and give you x(0.1) and not some extrapolation to x(1.1).

ndrz
Oct 31, 2003

I'm somewhat new to C, and we had a programming assignment to do. I completed the program, but I'm unhappy with what I wrote and was hoping for some clarification on the following code.

I have a function defined as int removeFirst(SortedPoints *sp, Point *ret). This function is called by a line such as retVal = removeFirst(sp1, &p1), where sp1 is a pointer to a SortedPoints object, and p1 is a Point object. SortedPoints has a pointer to a SPNode struct, which holds a pointer to a Point object, and a pointer to the next SPNode.

The goal of this function is to remove the first element in the SortedPoints list, and place the Point object it removes into ret. The function then returns a 0 or 1 based on success.

The code segment that I'd like to clarify is inside removeFirst, and is as follows: (I've omitted a portion of the code, I realize what is given here is an incomplete solution)

code:
SPNode *head = sp->head;

Point *x = head->data;
Point y = *x;
*ret = y;
This code works, and successfully updates ret. However, the last three lines look stupid. There's got to be a better way to do this, right? I kept trying to reduce it to 1 line, but I think I'm not understanding some pointer fundamentals. Things like *ret = ** head->data; weren't working, and I'm not completely sure why. Can anyone help me understand pointers a little better?

Dijkstracula
Mar 18, 2003

You can't spell 'vector field' without me, Professor!

Any time you have a pointer question, look at the data types and ask if what you're doing makes sense. (it's hard for us to know what they are since you didn't post the whole function)

I admit I don't really know what this code is trying to do - is it that you want to take head->data (which is a Point* ?) and store it in ret (which is also a Point* ?) ? If I'm understanding what you're doing correctly, ret = head->data is maybe what you want?

Also, this function is likely leaking memory like a sieve.

ndrz
Oct 31, 2003

Dijkstracula posted:

Any time you have a pointer question, look at the data types and ask if what you're doing makes sense. (it's hard for us to know what they are since you didn't post the whole function)

I admit I don't really know what this code is trying to do - is it that you want to take head->data (which is a Point* ?) and store it in ret (which is also a Point* ?) ? If I'm understanding what you're doing correctly, ret = head->data is maybe what you want?

Also, this function is likely leaking memory like a sieve.

You're correct in your assumption, but let me post more code to hopefully help clarify.

code:
typedef struct PointStruct {
  double x;
  double y;
} Point;

typedef struct SortedPointsNode {
  Point *data;
  struct SortedPointsNode *next;
} SPNode;

typedef struct SortedPointsStruct {
  SPNode *head;
} SortedPoints;

int sp_removeFirst(SortedPoints *sp, Point *ret)
{
  SPNode *head = sp->head;
  if (head == NULL)
    return 0;

  Point *x = head->data;
  Point y = *x;
  *ret = y;

  SPNode *second = head->next;
  free(head);
  sp->head = second;

  return 1;
}

int main(int argc, char **argv)
{
  SortedPoints *sp1;
  Point p1;
  int ret;
  ret = sp_removeFirst(sp1, &p1);
}
ret = head->data is what I tried at first, but p1 remains unchanged. It seems it passes a copy of the pointer to removeFirst, and if I do ret = something, p1 doesn't change.

The goal is that after calling sp_removeFirst(sp1, &p1), p1 holds the point that was removed.

One last disclaimer, I realize that asking homework questions is frowned upon in the thread; this is an assignment that I've completed and turned in, I'm only trying to understand this issue I'm having for future reference.

Dijkstracula
Mar 18, 2003

You can't spell 'vector field' without me, Professor!

coldfire07 posted:

It seems it passes a copy of the pointer to removeFirst
Indeed it does - C only passes by value. So, in this case, ret = head->data would overwrite the argument to the function, but would leave the original untouched. This is one of the purposes of pointers - you pass the address of the thing you want to change to a function, then inside it it dereferences the pointer and manipulates the original variable.

Since you want to copy the Point that head->data points to, overwriting the Point that ret points to, try *ret = *(head->data).

Also, can you spot your memory leak? :)

edit: I've forgotten the presidence for * and -> so I wrapped it around parenthesis to make it hopefully clearer.

Dijkstracula fucked around with this message at 01:10 on Jan 31, 2010

Adbot
ADBOT LOVES YOU

ndrz
Oct 31, 2003

Dijkstracula posted:

Indeed it does - C only passes by value. So, in this case, ret = head->data would overwrite the argument to the function, but would leave the original untouched. This is one of the purposes of pointers - you pass the address of the thing you want to change to a function, then inside it it dereferences the pointer and manipulates the original variable.

Since you want to copy the Point that head->data points to, overwriting the Point that ret points to, try *ret = *(head->data).

Also, can you spot your memory leak? :)

edit: I've forgotten the presidence for * and -> so I wrapped it around parenthesis to make it hopefully clearer.

That does seem to work. I could have sworn I tried that and it failed to compile, but apparently not. I understand it a lot better after your explanation.

Regarding a memory leak, the only thing I can spot is the fact that although the SPNode is freed from memory, the actual Point object isn't -- which is intentional since we're wanting to save it in ret, right? Of course, I could be missing something else altogether.

Thanks for your help!

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply