lainchan / λ

The C Programming Language

Koichiro · 2022-01-27 08:10
C (/ˈsiː/, as in the letter c) is a general-purpose, procedural computer programming language supporting structured programming, lexical variable scope, and recursion, with a static type system. By design, C provides constructs that map efficiently to typical machine instructions. It has found lasting use in applications previously coded in assembly language. Such applications include operating systems and various application software for computer architectures that range from supercomputers to PLCs and embedded systems. A successor to the programming language B, C was originally developed at Bell Labs by Dennis Ritchie between 1972 and 1973 to construct utilities running on Unix. It was applied to re-implementing the kernel of the Unix operating system. During the 1980s, C gradually gained popularity. It has become one of the most widely used programming languages, with C compilers from various vendors available for the majority of existing computer architectures and operating systems. C has been standardized by ANSI since 1989 (ANSI C) and by the International Organization for Standardization (ISO). C is an imperative procedural language. It was designed to be compiled to provide low-level access to memory and language constructs that map efficiently to machine instructions, all with minimal runtime support. Despite its low-level capabilities, the language was designed to encourage cross-platform programming. A standards-compliant C program written with portability in mind can be compiled for a wide variety of computer platforms and operating systems with few changes to its source code. Since 2000, C has consistently ranked among the top two languages in the TIOBE index, a measure of the popularity of programming languages. C was created by Dennis Ritchie at Bell Labs in the early 1970s as an augmented version of Ken Thompson's B. Another Bell Labs employee, Brian Kernighan, had written the first C tutorial, and he persuaded Ritchie to coauthor a book on the language. Kernighan would write most of the book's "expository" material, and Ritchie's reference manual became its appendices. The first edition, published February 22, 1978, was the first widely available book on the C programming language. Its version of C is sometimes termed K&R C (after the book's authors), often to distinguish this early version from the later version of C standardized as ANSI C. In April 1988, the second edition of the book was published, updated to cover the changes to the language resulting from the then-new ANSI C standard, particularly with the inclusion of reference material on standard libraries. The second edition of the book (and as of 2021, the most recent) has since been translated into over 20 languages. In 2012, an eBook version of the second edition was published in ePub, Mobi, and PDF formats. ANSI C, first standardized in 1989 (as ANSI X3.159-1989), has since undergone several revisions, the most recent of which is ISO/IEC 9899:2018 (also termed C17 or C18), adopted as an ANSI standard in June 2018. However, no new edition of The C Programming Language has been issued to cover the more recent standards. ITT WE C PROGRAM
Knuth · 2022-01-27 08:17
I am using the ANSI C Programming Language, the first standardized version of C. I originally wished to use K&R, move to the next, and so on but I discovered that modern compilers stopped supporting K&R C an unknown amount of time ago. The exercise in the screenshot is the solution to 1-4. It computes correctly but I forgot to fix the printf. C was designed to be a universal language like UNIX was a universal operating system. Much like UNIX, C was used nearly universally until the end of the last century. C remains a lovely programming language for portability, learning basic concepts, and making your own programs. Go was created by Rob Pike (of plan9 fame) to be a successor to C. Many former C programmers have chosen Go in favor of C. I wish to learn Go after I myself learn C. Image is my notes while beginning K&R, but it appears to remain true for ANSI C.
Frank Garza · 2022-01-27 08:20
>>29650 The ANSI C Programming Language, Second Edition https://libgen.fun/get.php?md5=556E6BEE561B776C95C6872C441BAAD1&token=5a49e2c27ad0ad6e7c This is the official book defining the standard.
Jens Hansen · 2022-01-27 08:23
More notes for K&R C which translate easily. I will my notes for ANSI C as I make them.
Neuromancer · 2022-01-27 08:42
Nice setup. What os you using?
Cypher · 2022-01-27 08:44
>>29656 I'm going to bed to begin programming again tomorrow. I spent too much time tonight trying to figure out how to compile K&R C only to discover that K&R was removed from GCC and other major compilers an unknown amount of time ago.
↑ · 2022-01-27 08:47
>>29657 Cheers. Sleep well soldier
progn · 2022-01-27 11:14
>>29649 That setup is so fuarrrking *comfy* that I almost want to pretend to be an ANSI C programmer again with you. My first programming language was C89 , and I can tell you there is no reason to prefer it to anything. Modern C is actually much better. The possible area of debate is modern C compilers which will ruthlessly optimize predicted on assumptions that your not relying on Undefined Behavior and don't behave like 'portable assembler'. Also, the C standard isn't actually enough to write any *real* program. It doesn't have basic features like creating a directory, checking file permissions, threading. In some ways, this is the beauty of C, the core is a simple language. You have to add POSIX to get a platform. Your setup is so fuarrrking based though that I almost don't care that your just writing for loops.
Erik Johansson · 2022-01-27 13:08
That setup in the pic looks rad as hell. >>29657 I guess you could use a novelty c environment, like plan9front for example. >>29660 K&R is fairly wonky from what i remember not much loss there, any opinions on c99 btw?
list · 2022-01-27 16:02
>>29657 >>29660 >>29661 Wait a minute, was buying K&R a bad thing? For context, I'm a newbie programmer who is interested in learning about things on the lower level.
qms · 2022-01-27 17:45
>>29662 No. buying the k&r is a very good thing. It's just a little outdated is all. pretty minor things like how the book uses `main()` instead of `int main()`. the k&r is a very very good book
Leto Atreides I · 2022-01-27 18:06
>>29662 >Wait a minute, was buying K&R a bad thing? For context, I'm a newbie programmer who is interested in learning about things on the lower level. Yes. Its a book for C from a different time. If you want a Deep and Comprehensive introduction to C, Robert Seacord, of CERT and "Secure Coding in C and C++" wrote an excellent book on C called "Effective C: An Introduction to Professional C Programming " - its worth a read. Zed Shaw has "Learn C Programming the Hardway" which is also good. K&R is a meme /g/ choice. K&R C doesn't exist anymore, nothing is written in it. Its typically taken as the best bottom up example of how to explain a language, and many excellent programming books have emulated it - "The Ruby Programming Language" for example. It may shine in demonstrating the structure of a good programming book, but what it directly teaches is obsolete.
Faye Valentine · 2022-01-27 18:15
>>29650 Go's got its qualities, but it's no C successor, even if Rob Pike would like you to believe otherwise.
Hououin Kyouma · 2022-01-27 18:16
>>29662 No it was not, first of k&r hardcover is always a good thing to have. It also is pretty much the same, there are some minor exotic syntax changes, but the concepts and syntax are all pretty much the same and if no compiler tells you. Btw anyone here made minigames with c? I kinda think of doing some for novelty value, maybe try it on 9front even.
qms · 2022-01-27 19:10
>>29666 Seacord's Effective C is a PIECE OF SHIT. I started out with the book and learned nothing. I know it's more modern, but it is not a good book for beginners. It pretty much went from "hello world" to arrays. k&r is a lot more in depth, making sure that the beginner will understand everything. Seacord's Effective C is only handy as an occasional reference
Chan Siu Ming · 2022-01-27 19:11
>>29665 `int main()` is actually bad practice. The function defined like that has no restrictions on what arguments type or number it can accept. The compiler will not warn you. Although its unlikely that you will be calling main(), using this syntax for other functions is unadvised, you should be using `int main(void)` to indicate no arguments. This effectively enables to understand the type of the function and issue appropriate error messages and warnings.
qms · 2022-01-27 19:12
>>29668 >Btw anyone here made minigames with c? I've some tiny little adventure games. While writing this im working on another. Still very basic newbie stuff, but im learning a lot by doing it. Here's the last one I did. Feel free to look through the source code & tell me if I did anything silly (or even send a pull request if you feel so inclined) https://github.com/QMaury/QAdventure2/
qms · 2022-01-27 19:13
>>29670 I keep hearing that but noones actually explained to me why. Well, thanks for telling me, that does sound like something I wanna keep track of
H.R. Giger · 2022-01-27 19:16
>>29669 My friend, I think you are a little delusion. There is no question that Effective C is a more in depth book than K&R. You may not want the depth. You may think the depth is out of hand for an introduction. But disputing the depth is non-nonsensical. Effective C covers semantics that weren't even defined semantics when K&R was created. Can characters have trap representations? When is the difference between indeterminate memory and memory that is unspecified? How do the usual conversions and integer promotion work in C. These kinds of questions don't have answers in K&R C - they weren't standardized - there was no standard or undefined behavior, only implementation defined with K&R being the implementation.
qms · 2022-01-27 19:20
>>29673 ok, maybe "depth" was not the correct wording. What I mean is that it doesn't give as good an introduction to newbs as the k&r. Memory allocation & other semantics like that are not as useful to learn early on as some of the operators and stuff like getchar & putchar.
Aristóteles Amadópulus · 2022-01-27 19:23
>>29674 You may be right, although K&R is something of a book like that in itself that it trys to work bottom up. Many other books give you more 'practical' perspective where you are learning a variety of topics at the same time to enable little programs. Zed Shaws, Learn C Programming the hard way , is like that. I enjoyed Effective C. Definitely one of the better books I have read on C , but maybe not for a beginner. Although it proports to be.
Spike Spiegel · 2022-01-27 20:55
>>29675 OP here. Interesting commentary that followed last night. I thought that K&R C was no longer supported as I could not get it to compile with proper output in the tutorial. Perhaps I had simply copied the examples down wrong. Regardless, it's certinally better to use a standardized version of something than its original form or its pidgin form. That's why when I made that other program here I tried to use POSIX instead of GNU or System V or BSD3 or something. ANSI C is the first standardized version, so I think it's probably better I'm learning the language using this than K&R anyway. I'll put more notes up as I go through the book later, as I have errands to run today. Last night, I made a lot of notes going through Chapter 1 of K&R but could not check my work through compiling so I immediately switched to ANSI and saw that the chapter 1 was essentially the same as the K&R Tutorial. I posted some of these notes already in the thread, and I hope that they are valid.
Hagbard Celine · 2022-01-27 21:49
>>29649 >>29657 seriously comfie setup lainon. how did you get your desktop icons and windows styled as such? is this default FVWM? I want to follow in your footsteps
Dox · 2022-01-27 22:22
>>29677 https://gitgud.io/se7en_gitgud/dotfiles
Cat Mother · 2022-01-28 11:09
>>29649 >>29650 >>29654 >>29657 Bitmap fonts are so sexy
Jane Doe · 2022-01-28 14:41
>>29662 I thought K&R was pretty good. clc-wiki has a nice list of multiple solutions [https://clc-wiki.net/wiki/K%26R2_solutions] #C wiki has some nice looking book recommendations [https://www.iso-9899.info/wiki/Books] >>29666 clc-wiki suggests against Zed Shaw's book [https://www.iso-9899.info/wiki/Main_Page#Stuff_that_should_be_avoided] but that ACCU really likes Effective C [https://www.accu.org/bookreviews/2021/sullivan_1964/]
Acid Burn · 2022-01-28 16:52
* Install Emacs, Neovim or VSCodium. * Use Clang or GCC. Also install splint, cppcheck, gdb, valgrind and afl. * Do use things like -fsanitize=address https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html * If you are looking for a GUI lib, use Tk. * Read The C programming language, 2nd edition by K&R and/or C Primer Plus, 6th edition by Prata * After K&R or C Primer Plus, read 21st Century C, 2nd Edition by Klemens * Follow a style guide: https://suckless.org/coding_style/ * Use a reference: https://en.cppreference.com/w/ * https://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html * https://lwn.net/Articles/250967/ * https://blog.regehr.org/archives/213 * https://dl.acm.org/doi/10.1145/103162.103163 or https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html Book recommendations for C++: * If you don't know how to program, read Programming: Principles and Practice Using C++, 2nd edition by Bjarne Stroustrup. (aka PPP2). * If you know how to program but don't know c++, read C++ Primer, 5th Edition by Stanley B. Lippman; Josée Lajoie; Barbara E. Moo.
Random · 2022-01-28 19:58
>>29672 >>29670 ya, on first inspection it seems wrong. how can you pass arguments to a function that doesn't define arguments?
Bob Arctor · 2022-01-28 20:36
OP here. I wasn't able to progress further yesterday due to one of my single errands taking an entire 3 hours of my day which just urked me. I'll be providing more notes for ANSI C later in the day. >>29686 The original person was right though, it's probably better to learn the standard definition of C first rather than the K&R original. This is why I switched over to ANSI C. I also could not get K&R to compile with expected output, so either I was doing something incredibly wrong or gcc no longer supports K&R. I have a lot of differing research on that. >>29688 I use emacs, GCC is my compiler. I know of gdb, but splint, valgrind, and afl are alien to me. I would think ccpcheck is short fot "C Compiler's Program Checker". I do not recomend using GUI libs at all presently. Anything you learn can be implemented later, after the bare fundementals. Implementing GUI at my level I would think would lead to confusion and would lead people to program exclusively for GUI rather than the fundementals. Nice style guide provided. Thanks for the links. C++ is disgusting crap
Sipho Nkosi · 2022-01-28 22:10
>>29691 Am I incorrect in my basic math or my code?
XERXES · 2022-01-28 22:11
>>29692 Oh, I misunderstood the question. I thought it had asked me to produce a reverse-order table like 1-4 had. Instead, the question was to change the statement to produce 300-0 instead of 0-300. In either case I clearly was wrong.
↑ · 2022-01-28 23:19
>>29692 Your code is also a little backwards, Celsius is an integer >int celcius but you print it as a float >printf("%5.1f %3d", celcius, ...) f corresponds to float, and celsius is an int.. Good Compiler warnings should catch this and prevent these kind of mistakes. >(5.0*9.0)*(32+celsius) you probably meant 5/9 , your multiplying celsius+32 by 45.0 rather than 1.8 Compiling with -Wall should hopeful give you error messages explaining this (but not 45.0 vs. 1.8).
roll · 2022-01-29 00:11
>>29696 This is the tutorial example from ANSI C
Chan Siu Ming · 2022-01-29 00:15
>>29696 This is the tutorial example from ANSI C. I had mistakenly believed that question 1-5 was the same as 1-4, which had asked to change the while statement to produce a Celcius to Farenheit rather than a Farenheit to Celcius. In doing so, I switched celcius and farenheit, and did the inverse of the mathematical operations to achieve the answer. Maybe I need a refresher in basic algebra too (it couldn't hurt regardless). But for the rest of your comment, this is how the example's code reads before modification: #include <stdio.h> main() { int fahr; for (fahr = 0; fahr <= 300; fahr = fahr + 20) printf("%3d %6.1f\n", fahr, (5.0/9.0) * (fahr-32)); }
Jens Hansen · 2022-01-29 00:23
>>29698 This code doesn't have the same issue. The issue is in the ordering of the types of the variable with the printf format codes , d must match with in integer type, and f must match with a float. This example correctly pairs an integer (fahr) with a d ,and float (5.0/9.0)*(fahr-32) with f.
Dozer · 2022-01-29 00:26
>>29699 So in order to answer 1-4 for this for statement, would I then do the same, except evaluate cel =0, cel <=300; cel = cel + 20, then print as it is in the original, but change my arethmetic to (5.0*9.0)/(cel-32) to produce the correct answer? The problem in my attempt is twofold, not only corrupting the printf string to be 'backwards" as you say but also the conversion of the basic arethemetic to convert not from the original F to C, but from C to F.
array · 2022-01-29 00:27
>>29698 ANSI C is also teaching you weird habits that no longer apply. Its idiomatic C to declare variable used as loop index inside the loop. for(int fahr = 0; fahr <= 300 ; fahr = fahr + 20) ... ANSI C code usually starts like your example with a giant list of declarations of variables which are unclear what are to be used for. General purpose stuff like `int i;` . Its currently considered a best practice to define a variable as near to where its used as possible, to help the reader understand its type and values. For your program, this isn't an issue at all. But you can imagine larger more complex programs with giant lists of declarations.
Technician · 2022-01-29 00:28
>>29701 In such a case, should I stop using ANSI C? I had an entire process I wanted to do, learn K&R then learn ANSI, then learn C99, then learn C2018. If you think that I am learning obsolite bunk then maybe I should just use a recent book.
Splicer · 2022-01-29 00:35
>>29700 >but also the conversion of the basic arithmetic to convert not from the original F to C, but from C to F. The formula isn't correct. There is an algebra mistake, and probably a typo. Your multiplying by 5 and then by 9, thats the same as multiplying by 45. Take 100 Celsius, which you know corresponds to 212 F. Multiplying 132 * 45 gives a number way above 212. There was probably supposed to be a division in there. There is also an algebra mistake. You have to multiply/divide before adding when doing algebra. For instance: x = z ( y + a) x/z = y+a x/z -a = y V.S. Incorrect: x = z ( y+a) x -a = zy (x-a) / z = y > only corrupting the printf string to be 'backwards" You can switch the order of the things you just have to do it consistently. Lets do an integer and a string. Strings use format code "%s" printf("%s %d\n", "Hello", 5); swapped consistently printf("%d %s\n", 5, "Hello"); At all times, %d is paired with 5, and %s is pared with "Hello".
limited · 2022-01-29 00:37
>>29702 I feel stupid but I have made no attempt to claim that I am not a beginner. I'm not even past the first chapter and I'm having these issues. I've only been on this for two days or so now though, and I haven't had time to just sit down and study it like I did for that POSIX shell script that I worked about 4 days on. I hope that I am not fooling myself here. I would have been much further had it not been for the busy errands I had to do over the past few days which have brought me away from my workstation. But as a beginner, I truly thought I could just go book by book, eventually learning this then Go, then Pascal, then LISP, then all the other petty languages. It seems that my first choice, K&R C, has proven to be too obsolite to begin with so I went to ANSI C Second Edition. Now it appears this also is too obsolite to begin with. What then should I use? C99? >>29703 Is the language literal in its order and not respecting PEMDAS? If so, I was unaware but was suspecting of such. I think that I should perhaps put this on hold and take a quick Algebra refresher course if these basic problems are not primarily of my code quality but of basic math.
let · 2022-01-29 00:38
>>29702 >should I stop using ANSI C? I had an entire process I wanted to do, learn K&R then learn ANSI, then learn C99, then learn C2018. If you think that I am learning obsolite bunk then maybe I should just use a recent book. Anything is better than nothing. Staying motivated is more important that picking the "best" route. The stuff you are doing now with ANSI will easily translate to C99 and to C17. But, you will just find ANSI C as slightly quirky and a little limited compared to later versions. C99 is still recommended by many guides. C17 isn't meaningfully different but does add a few features. If working from this book is what motivates you to work, then keep doing it.
Trinity · 2022-01-29 00:47
>>29704 >Is the language literal in its order and not respecting PEMDAS? It depends on what you mean. The formula for conversion is done in done with PEMDAS, but there is just a simple algebra mistake. Your given > C = 5.0/9.0 * (f-32) Move the 5 and 9 over to the other side first. 9.0/5.0 * C = f - 32 Move the 32 over next. (9.0/5.0 * C) + 32 = F You have > F = 5.0 * 9.0 * (C+32) Notice how these are different. Its not stupidity, its just a bug. Programmers do this all the time. >PEMAS and printf Printf takes the % codes, called 'format specifiers' one after the other in order and then pairs them with the arguments after the 'format string' one after the other in order. >printf("%6.1f %3d", celsius, 5.0*9.0*(celsius+32)); pairs '%f' with celsius which has the type integer, while %f indicates the type float. pairs '%d' with the 5.0*9.0*(celsius+32) , which is a float. They are paired one after another.
fsociety · 2022-01-29 00:51
>>29704 >book by book, eventually learning this then Go, then Pascal, then LISP, then all the other petty languages. Another thing to consider is that programming languages are mostly not like human languages. Learning new ones *can* teach you new ideas about how programming is done, but *mostly* will not, specially in the beginning. Far more important is spending time in your language working on a variety of problems. So, I wouldn't rush to learn as many languages as you can. You will find go has the same for loops as C and so one, with a little variations. One programmer can easily pickup another language (in the same paradigm), and write, but not idiomatically and artfully. Is way too easy to get sucked into an endless series of tutorials and never actually learn the valuable skills.
Pulse · 2022-01-29 00:58
>>29707 A fair point. I have nothing scheduled until Monday and have little money or drive to do anything outside over this weekend so I think I can really dedicate myself to this tonight through Monday like I did for that activist POSIX script. Of course, I was already much more familiar with UNIX than I was with C when I started, but I improved significantly in my knowledge over those few days. Ken Thompson is quoted as saying that C is more advanced but most people can get around fine with just the UNIX shell. I think that I am finally ready to get to the more-advanced C having become proficent (but not fully expert) in that shell.
aliased · 2022-01-29 01:05
>>29708 If you care for it, because your programs are so small, you could try writing them in both languages and compare. Bash can produce a table like you are trying in just a couple lines.
Cereal Killer · 2022-01-29 01:09
>>29710 That was the original plan, and the kick in the ass I needed to start learning a programming language again after 10 or so years, but I think I should get to at least chapter 3 or so to know the basic fundementals before I try. >Bash can produce a table like you are trying in just a couple lines. These aren't my programs, these are the tutorial examples from the book. I already know shell as I've said, and am moving on. I'm the author of >>29622 which I will convert to a C program once I am ready enough.
Chan Siu Ming · 2022-01-29 01:17
>>29711 Here is an example in bash, which I haven't written in a while: for celsius in {0..300..20} ; do printf "%b\t%b\n" $celsius $(echo "scale=2;$celsius*1.8 +32;"| bc); done Comparing with the syntax in the book, you can really see how C shines at making mathematics easier to do. Bash has sub-processes, piping.
Leto Atreides I · 2022-01-29 01:21
>>29712 I'm aware, yes. I already said that. I'm moving up from that, I said. You're trying to get me to move backwards. In fact, you're trying to get me to move backwards even father because you're asking me to do Bash instead of POSIX-standard Shell. I did Bash for years before learining proper UNIX, as well as the differences between System V, and BSD3, then finally learning standardized POSIX. Now I'm finally ready to learn a full Turing-Complete rather than a simple programming script and you want me to do Bash? Heh.
Jens Hansen · 2022-01-29 02:29
I've been seeing you struggle with C standards. Like for example the language in K&R. I wonder, are you really using K&R 1st edition? If you're using 2nd edition, the book uses ANSI C which I believe should still be supported. But more importantly, the language is essentially the same, and you should get used to working out discrepancies between different versions of the standard, and work your way through K&R2 and reading the warnings and errors to figure out why and how ro fix them. In a sense, every programming book I've ever read misses my setup by just a little bit. The book uses x86_64 where my computer is 32-bit, etc. These minor issus kept me from progressing for a while. But what's relly important ae the general concepts and not the implementation details. Now, what are your general goals? Do you wish to understand the inner workings of your system better? Do you wish to make systems programming, kernel hacking, general programming? Is it for edifiaction, or do you have a specific application in mind? Do you have a specific domain in mind? Say, cryptography, networking, compilers, scientific programming? All of these considerations should be taken in mind so as to get you from A to B. Else (and this apllies to standsrd-purism as well) you're dispersing energy you would do better in focusing because, let's face it, learning can be hard.
byte · 2022-01-29 02:50
>>29714 I was on K&R First Edition. Now I'm on ANSI C Second Edition, which I posted at >>29652 As for my motives for learning the language, I have many including employment but also to understand my computer and general computation more. I never went to a University but I want to persue a STEM career. I value all four. I wanted to teach myself this stuff nearly a decade ago now but was repeatedly interupted so I never exceled beyond UNIX itself. I know no Python, Perl, SmallTalk, anything that's turing-complete really. I believe that I have the ability to pick this stuff up fairly quick, then over a gradual process be able to move to high-proficiency just as I have for UNIX. I also finally have the stability and the time to do this too. I want to know how to do this to make my own programs and also be able to claim the advanced knowledge. My experience thus far includes Microsoft BASIC 8 UNIX (Linux) UNIX (POSIX standard) Markup (Various) General modification of programs, editing of makefiles, editing of minor parts of larger programs. SCIP Video Series (but not SCIP book) An attempt at making a MUCK A large amount of computer theory, computer anthropology I'm sure there's more in there, but it reflects my current level of understanding. I'm finally making the leap into being Turing-Complete. Far beyond this simple programming for the end-user on his little dinky comp. The Turing-Complete Programmer is the big leagues, working at Bell or one of those fancy companies, who understands the deepest aspects of the recesses of our common technology. He programs on his mainframe, and serves as a backbone to the entirety of every computer user. User vs Programmer. I have a workstation. I better well use it. C is the next level up from UNIX. I am progressing in the correct order, I believe. I will learn the arcane truths of this wonderous logic machine which mankind hath created, and learn its pure language.
Zuse · 2022-01-29 04:52
>>29715 I've been so distracted all day it's hard to sit down like it was the rest of the week. I'll keep uploading as I go, and eventually upload this file of my notes.
Wirth · 2022-01-29 05:06
Thanks for making this thread OP. I'm in uni for software engineering but felt I never really learned much actual programming fundamentals. I've always been really interested in learning C/C++ but always stopped because I'd always get stuck on some basic concept and procrastinate. I started working through a C++ text book a couple months ago and dropped it but I really want to get back on it. I've been lurking a bit and am starting to make my way through learning C rather than C++, not skipping any exercises or taking any shortcuts until I understand it. Seeing someone else struggle like me and power through really motivated me to give it another try and stick with it. really do appreciate you
The Oracle · 2022-01-29 05:14
>>29716 Already into the problems again. I have the whole weekend and am an insomiac so get ready.
Gyula Kovacs · 2022-01-29 06:06
>>29718 Just to show some progress after about 30 minutes of doing other nightly tasks. My speculation is that EOF can not display to the terminal, and as such I can not simply printf EOF. The exact question asks to check if getchar() != EOF is 0 or 1. This means is it true or false. This is the first time a check like this has been asked to be performed by the student. 1-6 asks to verify, and 1-7 asks to print the value. I am confused (as you can see by my previous if statement) what exactly the book is asking me to do as if statements have not yet been covered.
Armitage · 2022-01-29 06:41
>>29719 I was wrongfully told that there was a C Programming subsection of Stack Exchange https://stackexchange.com/search?q=C+Programming I tried looking for an answer book for ANSI C to assist me further but found none. https://searx.fmac.xyz/search?q=Answers+to+ANSI+C&category_general=on&theme=oscar&language=en The problem is probably incredibly easy to solve, but I am unsure of several things including what the question is asking to do when it uses the word "Verify" if it is true or false, and further how exactly I am to print EOF if it does not appear without an ugly hack.
Switch · 2022-01-29 06:44
>>29720 I just had to reload the page, silly me
Wintermute · 2022-01-29 06:46
https://seriouscomputerist.atariverse.com/media/pdf/book/C%20Answer%20Book.pdf My PDF upload was discarded
Dox · 2022-01-29 07:06
>>29722 I see nothing in 1.5 that talks about using '= unless it means !=, and the word at confuses me. As for the answer to 1-7 I understand what this is doing. I probably got too confused because I tried to make an if statement instead of what it already talked about, a while statement, then went on a wild goose chase confused. I'll continue on to the next task. I assume that the special things in 1-6 are required because EOF is an invisible character, but I thought you could evaluate it to either true or false, then produce its status code to the terminal as either 0, or 1 (or in the case of the author of the answer sheet
Mitnick · 2022-01-29 07:15
>>29723 There was no exercise for 1.5.2
Shogun · 2022-01-29 07:28
>>29724 We're kicking it off now with 1-8, asking to write a program to count all three, blanks, tabs, and newlines.
Church · 2022-01-29 07:34
>>29726 As I do not have the notes for each special character, I need to find a reference sheet. https://www.petefreitag.com/cheatsheets/ascii-codes/ It looks simple, the ones I need are simply \t for tab, and literal space
St. IGNUcius · 2022-01-29 07:46
>>29727 1-8 solved, now 1-9 is incorrect. I'll try to figure out the answer here.
Davis · 2022-01-29 07:54
>>29728 I realize that what I did resulted in actually increasing the UTF-8 character representation by 0x3. That's also quite a learning experience in my mistake, though I already knew it was possible. The problem presented is to make a program that adds a space to each inputed character: example, input 'Hello' outputs 'Hello '. I wonder if I need to use a printf statement for this, or if I can simply eval like this program originally did, then add a space to the eval. Either way, this (which is a persuit of the latter) is wrong.
Trinity · 2022-01-29 08:21
>>29729 The answer has to be some kind of combination of the two previous programs, the one to count all three, and the one to output one. Specifically, the question asks to produce a program that is space space space -> space So I again misread the question initially. That recurrance might be a growing problem. So something along the lines of If a character string has more than one space, undelineated, remove the undeliniated spaces from this string. In the previous exercise we learned how to count each character. In the previous lesson, we learned a program for returning input that was recieved, without any process. Therefore, the solution must be some combination of the two, where the input is tested, and only when space is counted to be >1, remove all exces spaces until space = 1. It's asking to make a program removing trailing and excess whitespace, essentially. A more complex version could obviously also add spaces, so you could process text to be single space, double spaced, tripple spaced, and so on. Now that I've figured out the order, I need to actually figure out how to implement that in C with all that I've learned up to this point....
Cutter · 2022-01-29 08:30
>>29730 I couldn't figure it out, so I looked it up. This is the answer key for 1-9. I would not have thought you'd need to redefine space
Eldon Tyrell · 2022-01-29 08:34
>>29731 The answer book continues its answer on the next page
Judge Fang · 2022-01-29 08:39
>>29732 1-10 was literally the previous program, except it adds printf statements to have literal backslash to display characters. Every invisible \t suddenly appears.
list · 2022-01-29 08:59
>>29733 Well, some more notes on this. I think it's interesting. I still am not out of the first lesson, I'm only halfway through it, and I'm still having these problems for basic understanding. This is supposed to be a tutorial. If anyone wants to chime in on potential resources to help me in this persuit, and those that read this in whatever archived form it will be in, be my guest.
Nell · 2022-01-29 09:08
>>29734 Some more notes, some more attempts at doing basic programming.
Koos van der Merwe · 2022-01-29 09:11
>>29735 I fixed all of my typos, but I can't fix typos in a book from the 1980s. Is that a typo? It doesn't match the other arguments.
Lady 3Jane.. · 2022-01-29 09:40
>>29736 The expected student answer
swap · 2022-01-29 09:42
>>29738 I am able to understand this answer but I am not able to get to that answer. An interestig problem. Anyways, I think a break is needed.
Roger Pollack · 2022-01-29 09:48
>>29739 I also see that there are a lot of C courses on YouTube, but they are mostly made by Indians. I hope to find some better coursework, which I will watch secondary to using this book and hopfully will be able to learn faster. As I said I already watched some of the SICP video lecture series, but haven't done the book. Now I'm trying to do the inverse, learn C with a book that has no accompyning video series.
Y.T · 2022-01-29 12:23
>>29716 Your table of values is incorrect. 0 Celsius isn't 57.6 Degrees Fahrenheit, and 100 C isn't 237F. You should one or two of these conversions by hand, and then compare with your program to be sure you are correct. You fixed the typo (changing 9.0 * 5.0 to 9.0/5.0) but there is still an algebra mistake. You can also 'look up' the formula online and compare with yours and see why you aren't getting correct answers. You have figured out how to successfully pair format specifiers with types, so that's good, you are making progress. You have a warped understanding of programming. 'Turning Complete' is a technical term. Bash is Turing complete. Latex is Turning Complete. Turning Completeness has the ability to do with being able to emulate a simple class of computer fully , and that computer being capable of any computation - but not necessarily in the most convenient way (see. Turning Tarpit). C isn't a better bash. Shells were written by C programmers because they have a use. I have been tempted to write programs (lately converting blocklists to DNS RPZ format, and I found on line of AWK to be the right answer). Eric Raymond (ESR) rights about this is The Art of Unix Programming. Further, POSIX Shell or Standards aren't necessarily superior to implementations. It really depends on the context. For instance, most OS Security features are non-standard. Do you want to pledge/casper/seccomp ? How about epoll() vs select ? There are probably scripts that should be written in POSIX Shell - perhaps initscripts for a service designed to run on various embeded platforms, BSDs, and Linux. In fact, the posix standard is even broken in some ways. One example is link(). Link() should always produce a hardlink, yet link() a symlink and you will get a symlink(). Developers have found it more convient not to align with POSIX. Bash even had an environment variable called 'POSIX_ME_HARDER' to ensure standard compliant behavior, even when that behavior was undesirable - the variable is now renamed, but the sentiment is real. Standards arn't a wonder of correctness, they put together ideally by freezing things that have settled as 'the way' by various POSIX users , by a variety of actors, who all have to own intrests, and sometimes don't settle things established but their own things for their own reasons. Turning Completeness is a technical term that has nothing to do with the value or usefulness of a language. Learning the languages in order will not improve your ability to understand them but maybe will give you an appreciation for the ease in which modern languages can concatenate strings.
Church · 2022-01-29 12:37
>>29691 >splint, valgrind, afl and ccpcheck splint and cppcheck are static code analysis tools. i.e. they help you to find bugs. clang also has its own static code analysis tool. Valgrind helps you to catch and analyze memory bugs. afl let's you fuzz your program. i.e. test it with random input and see if it encounters a bug.
list · 2022-01-29 20:35
>>29741 In such a case, what do you recommend for someone at my level if not ANSI C? Do you believe I should halt my efforts and take an algebra referesher course?
x<->y · 2022-01-29 20:49
>>29688 >>29743 I have installed all your recommended tools and have yet to use them. You have linked a paper hosted on ACM which I do not have access to. I don't think I'll ever have access as I am not a member of any University, and do not want to spend money on it regardless of member or non-member price. As for your other papers, they look interesting and I will study them just the same. I already know a lot about computer memory, but I feel I can learn much more from the LWN article. Interesting how your LLVM article has a URL saying "What Every C Programmer Should Know" when it resolves to an article titled "What Every C++ Programmer Should Know". You also link cppreference.com, which is for C++. I have been led to believe that C++ (much like C#) is a completely butchered and ugly C dialect that implements OOP in a stupid way, which forces the programmer to write code that is needlessly longer than its C equivilent. The author of the language, Bjarne Stousturp is quoted in this 1998 interview to IEEE: >Stroustrup: Well, one day, when I was sitting in my office, I thought of this little scheme, which would redress the balance a little. I thought ‘I wonder what would happen, if there were a language so complicated, so difficult to learn, that nobody would ever be able to swamp the market with programmers? Actually, I got some of the ideas from X10, you know, X windows. That was such a bitch of a graphics system, that it only just ran on those Sun 3/60 things.. They had all the ingredients for what I wanted. A really ridiculously complex syntax, obscure functions, and pseudo-OO structure. Even now, nobody writes raw X-windows code. Motif is the only way to go if you want to retain your sanity.. >Interviewer: You’re kidding…? >Stroustrup: Not a bit of it. [...] http://harmful.cat-v.org/software/c++/
Spooky · 2022-01-29 21:30
>>29715 >The Turing-Complete Programmer is the big leagues, working at Bell or one of those fancy companies, who understands the deepest aspects of the recesses of our common technology. He programs on his mainframe, and serves as a backbone to the entirety of every computer user. User vs Programmer. I have a workstation. I better well use it. Well, Turing-complete is no such a big deal, really. Python and js are turing complete, and their userbases know next to nothing, and limit themselves to putting libraries together like legos. They get a great deal of work done that way, too. Actually, I understand that a lot can be done with a shell and it's utilities. I personally like network stuff, and a great deal can be done with just netcat and awk. But I understand where you're coming from. Keep it up studying C. A word of advice, though. C is no silver bullet, some things are too difficult to build with just C. And there is a lot to know, no one person can really cover it all in depth. C takes you in one very specific direction, a very interesting one at that. When you're ready to move on, I suggest checking "Computer systems, a programmer's perspective" and "the design and implementation of the FreeBSD operating system".
byte · 2022-01-29 21:35
>>29752 Thank you for these pointers. As I said last night I think it's probably a good idea to augment learning ANSI C with wathcing one of these tutorial presentations on YouTube, but I don't know who is good and who is not. The majority of results I see appear to be Indians, which is an immediate avoid. After I become proficent enough in C, I hope to be able to put it on my resume (as I have done for UNIX) and then move on to other professional languages which I have already listed here, including its (debatable) successor Go, SmallTalk, and Pascal. Maybe Fortran and Haskell would be nice too for some comfy employment oppertunities. LISP is also a must, but since SICP was a 601 course, I think that's probably farther down the line. Besides employment, it's also the ability to learn and understand it. It's a personal goal.
Unknown · 2022-01-29 22:56
>>29754 I would discourage Pascal as I've hardly heard of it in the past decade. As for Fortran, well, it's a gamble. Do you plan on doing physics programming? The majority of science has migrated to python and R anyway. As for Lisp, don't be scared. It may pay to read he Little Schemer when you're done with C, it's a really simple language, really.
Joe Bloggs · 2022-01-29 23:22
>>29758 https://en.wikipedia.org/wiki/Real_Programmers_Don%27t_Use_Pascal Is this valid?
Jens Hansen · 2022-01-29 23:27
>>29758 >>29758 https://en.wikipedia.org/wiki/Real_Programmers_Don%27t_Use_Pascal http://www.ee.ryerson.ca/~elf/hack/realmen.html Is this valid? I read this years ago and it inspired me. Now I'm learning actual programming, and I see other people talking about compared to what it talks about is so behind the times it is either sadly lost-forever concepts OR it is a desperate clutch at something that no longer is needed. I prefer (as I'm sure you can assume by my posts in this thread) the former, in which the Real Programmers are the long-dead with their basic concepts lost to the Quiche Eaters who have won out.
Jane Doe · 2022-01-29 23:34
>>29760 In the same respect of the essay, ESR recently (2017) began a new document called "Things Every Hacker Once Knew" http://www.catb.org/~esr/faqs/things-every-hacker-once-knew/
sage · 2022-01-30 00:05
se7en, y'all, this is the c thread, in this thread we c program. ESR rambling about what it was like in the 70s, arguments about pascal and fortran, I think youre getting a bit off topic. I wouldnt complain but I considered derailing this thread earlier and stopped out of respect. Now I have a vested interest in keeping you on track. Hop to it, mister. Get compilin'
H.R. Giger · 2022-01-30 00:26
>>29762 Of course, my apologies. As I've been coding mostly as an end of day exercise I'm going to begin coding much later today. For now, I continue to listen to my subliminal improvement tapes (YT: 30 Minute Mindset is pretty damn good) that have been helping me, and also seek a C Programming Course on YT divorced from Indianism
dictionary · 2022-01-30 00:57
>>29763 I notice immediately from watching this video from Giraffe Accademy that his commenting style is RADICALLY different from what I learned to be valid comments. However, I think that this probably covered the entire first chapter of my ANSI C book. https://invidious.snopyta.org/watch?v=3lQEunpmtRA Now onwards to more tutorials!
renames · 2022-01-30 00:58
>>29766 He has made a playlist for a full course, which is 30 videos long. https://invidious.snopyta.org/playlist?list=PLLAZ4kZ9dFpMlt_8ZAs3ltQNeVQ9WITia
Nemissa · 2022-01-30 01:19
I made the following using what I just learned from these two videos and it does not compile. My compiler is /filled/ with errors. I guess I went too fast again. Interestingly, every single error is from stdlib.h, which I have not used until now (at the instruction of Mr. Dane). I do not see why I have to import the standard library at all when I am making no calls to it. I understand the need for <stdio.h> however because since ANSI C many of the basic elements of the program are stored in this header file which allows the compiler to simply import them. But I stress that every single error produced in my compiler is from <stdlib.h>. #include <stdio.h> #include <stdlib.h> /* Madlibish */ int main { char name[10]; printf("Enter your name: "); fgets(name, 10, stdin); char age[2]; printf("Enter your age: "); fgets(age, 2, stdin); printf("There once was a man named %s\n", name); printf("He was %d years old\n" age); printf("%s did not like his name", name); printf("%s did not being %d years old" name, age); return 0; } I'll keep watching Mr. Dane's course (as this is the result of combining what I saw in his tutorial, and what I saw in Lesson 6) and come back to fixing this basic program.
DEBUG-CONTENTS · 2022-01-30 01:20
>>29768 And yes, I have since noticed that age is supposed to be int or float (int in this case), but I forgot to recopy after I saved the changes. Doesn't fix compiler errors.
byte · 2022-01-30 01:34
>>29769 Going further in the lesson, he did what I did, except didn't implement the fgets for user input. It seems a minor typo produced the 900+ errors screaming at me for <stdlib.h> It finally compiles but does not produce expected output
Vasya Pupkin · 2022-01-30 01:35
File is output. Forgot to attatch.
over · 2022-01-30 01:36
>>29771 My assumption is that fgets is completely incompatible with non-character values.
vector · 2022-01-30 01:42
>>29772 fgets is short for file get _string_, yes.
Agent Richard Gill · 2022-01-30 01:44
>>29770 > It seems a minor typo produced the 900+ errors screaming at me for <stdlib.h> It's usually sage to focus on the first error. Subsequent ones may j be results thereof.
Lord Nikon · 2022-01-30 01:52
>>29774 Well, the lesson course has not yet gotten to User Input, so what's the proper way to do what I just did
Lain Iwakura · 2022-01-30 02:07
>>29776 Hmm. Finally in User Input, and I left the video to try to use what I just saw. Works, but has some clunk
Technician · 2022-01-30 02:24
>>29777 (self-check) I have improved the program now (though the newlines are expected, so says Giraffe Accademy). I did not know how to do this so I looked it up. This is the example provided, but I'm sure it's possible to do this without having to rely on a <time.h> library. It looks clunky to me, and like a needless hack.
Crash Override · 2022-01-30 02:40
>>29778 The individual I am watching continues on to claim that scanf() can only parse one argument at a time, and you have to specify each var after a new charstring. Certinally there's a way to actually implement all input, rather than have to seperate them, right? The next lesson is arrays. Hopfully this covers it.
Lunch · 2022-01-30 02:45
>>29778 How else would you know someone's date of birth if you don't know when they gave their age? Imagine running the same program with the same input in 10 years. It has to know the current year.
roll · 2022-01-30 02:46
>>29780 What I meant is accessing the current year using an imported library, why must I do that instead of getting it from the systemclock directly in the codepage?
Y.T · 2022-01-30 03:02
>>29779 Fun array fact: they're secretly pointers. C #include <stdio.h> int main() { char* name[] = {"so", "this", "works"}; printf("%s %s %s\n", name[0], 1[name], *(name + 2)); return 0; }
Milner · 2022-01-30 03:05
>>29781 Where can I find the source for <time.h> to see the function it is calling, current_time? All I can find are examples of its implementation, and examples for its use in ISO (such as pic related).
XERXES · 2022-01-30 03:27
>>29783 You would have to look at the source code for your libc implementation. For glibc on Linux it seems to be just a syscall https://stackoverflow.com/questions/44893766/#44900411
Roy Batty · 2022-01-30 03:31
>>29783 This auto-returned explanation (1) is self-contradictory. The explanation on Stack Overflow (2) is what I had assumed to be true. Therefore, there should be a published source of the contents of time.h, if not on my computer itself. I found the git for glib, and have found that everything in the sourcetree for "time" is an uncompiled c file. https://sourceware.org/git?p=glibc.git;a=tree;f=time;h=43c42a2127ac510ac726a197aa2b2757fcb9b1e9;hb=HEAD I was then unable to find the GNU implementation of current_tim, I do not see it in the directory. I also searched for tm_year and did not find it. It also is not in the subdirectory bit/ or sys/. However, a file named sys/time.h DOES exist. Looking through it I see no reference to the called arguments. https://sourceware.org/git?p=glibc.git;a=blob_plain;f=time/sys/time.h;hb=HEAD It calls bit/types/time_t.h (and others) so I decide to recheck those files. https://sourceware.org/git?p=glibc.git;a=blob_plain;f=bits/time.h;hb=HEAD These libraries appear to be a structured mess.
John Titor · 2022-01-30 03:37
>>29784 >>29785 Thank you for the information. I do not think I am yet ready to go to ring 0 and start fuarrrking with syscalls, but I was very curious how <time.h> worked in the first place as I believe the use of external libraries should be avoided at all costs, for a purer language. This is of course is needless in the course of a /compiled/ program, I suppose, but I'm sure it's still considered best practice. People like Terry were unafraid to fuarrrk with syscalls. His entire TempleOS was running at ring 0. I just am not ready. However, is there a way to emulate ring 0 programming so that if I fuarrrk up my computer doesn't explode, or brick, or overheat?
Otto Normalverbraucher · 2022-01-30 04:52
>>29783 /usr/include iirc is where all .h file are located. It's a good habit to look at them.
Naomi Nascimento · 2022-01-30 05:04
>>29787 Yes, thank you. It's all right there.
Jim Hilger · 2022-01-30 05:38
>>29788 I did not upload the program as it is now before I took a break. #include <stdio.h> #include <stdlib.h> #include <time.h> /* Madlibish */ int main() { int age; char name[10]; printf("Enter your name: "); fgets(name, 10, stdin); printf("Enter your age: "); scanf("%d", &age); /* is a pointer */ printf("There once was a man named %s\n", name); printf("He was %d years old\n", age); printf("%s did not like his name\n", name); printf("%s did not being %d years old\n", name, age); time_t s, val = 1; struct tm* current_time; s = time(NULL); current_time = localtime(&s); printf("He was born in the year %d\n", (current_time->tm_year +1900) - age); return 0; }
Ender · 2022-01-30 05:52
>>29789 #include <stdio.h> #include <stdlib.h> /* Needed for Most-Modern C */ #include <time.h> /* Library file in C dialect for calling Time in Syscall */ /* This program asks for a name, and an age, and tells the person * how old they are. WIP */ int age; int timeFunc() { time_t s, val = 1; struct tm* current_time; s = time(NULL); current_time = localtime(&s); printf("He was born in the year %d\n", (current_time->tm_year +1900) - age); } int main() { char name[10]; printf("Enter your name: "); /* fgets(name, 10, stdin); */ scanf("%s", &name); printf("Enter your age: "); scanf("%d", &age); /* is a pointer */ printf("There once was a man named %s\n", name); printf("He was %d years old\n", age); printf("%s did not like his name\n", name); printf("%s did not being %d years old\n", name, age); timeFunc(); return 0; }
Delilah · 2022-01-30 05:56
>>29790 Now what is wrong with my main program? int main() { printf("Enter your name: "); /* fgets(name, 10, stdin); */ scanf("%s", &name); if (name == "Bobby") /* compiles but does not work */ printf("Damn it, Bobby!"); printf("Enter your age: "); scanf("%d", &age); /* is a pointer */ printf("There once was a man named %s\n", name); printf("He was %d years old\n", age); printf("%s did not like his name\n", name); printf("%s did not being %d years old\n", name, age); timeFunc(); return 0; }
The Fin · 2022-01-30 06:06
>>29791 #include <stdio.h> #include <stdlib.h> /* Needed for Most-Modern C */ #include <time.h> /* Library file in C dialect for calling Time in Syscall */ #include <string.h> /* Adding all these libraries feels dirty */ /* This program asks for a name, and an age, and tells the person * how old they are. WIP */ int age; char name[10]; int timeFunc() { time_t s, val = 1; struct tm* current_time; s = time(NULL); current_time = localtime(&s); printf("He was born in the year %d\n", (current_time->tm_year +1900) - age); } int main() { printf("Enter your name: "); /* fgets(name, 10, stdin); */ scanf("%s", &name); if (strcmp(name, "Bobby") == 0 ) { printf("Damn it, %s!\n", name); } if (strcmp(name, "MUD") == 0) { printf("Your name is %s? Well, you the most borin'-ass son o' a...\n", name); } printf("Enter your age: "); scanf("%d", &age); /* is a pointer */ printf("There once was a man named %s\n", name); printf("He was %d years old\n", age); printf("%s did not like his name\n", name); printf("%s did not like being %d years old\n", name, age); timeFunc(); return 0; }
limited · 2022-01-30 06:30
>>29792 > Adding all these libraries feels dirty A nicer way of thinking about it is that all the libraries you don't need are not included. Compare C's minimalism to Java's cantankerous javax.* and it's no wonder C has a reputation for being a 'fast' language.
Agent Jones · 2022-01-30 06:42
>>29793 We are now too big to show on the screen! #include <stdio.h> #include <stdlib.h> /* Needed for Most-Modern C */ #include <time.h> /* Library file in C dialect for calling Time in Syscall */ #include <string.h> /* Adding all these libraries feels dirty */ /* This program asks for a name, and an age, and tells the person * how old they are. WIP */ int age; char name[10]; int timeFunc() { time_t s, val = 1; struct tm* current_time; s = time(NULL); current_time = localtime(&s); printf("He was born in the year %d.\n", (current_time->tm_year +1900) - age); } void mud() { /* if (strcmp(name, "MUD") == 0) */ printf("%s wanted to be called Aloysius Devadander Abercrombie\n", name); printf("He told me that it was short for %s\n", name); printf("Then he told me that he was told that!\n"); printf("What a strange kind of guy who \"drinks his wine\"\n"); } void bobby() { /* if (strcmp(name, "Bobby") == 0) */ printf("He thought that %s wasn't TV ready", name); printf("He thought the name Dale was better."); } char otherkin[] = "My Little Pony"; int main() { printf("Enter your name: "); /* fgets(name, 10, stdin); */ scanf("%s", &name); if (strcmp(name, "Bobby") == 0 ) { printf("Damn it, %s!\n", name); } if (strcmp(name, "MUD") == 0) { printf("Your name is %s? Well, you the most borin'-ass son o' a....\n", name); } printf("Enter your age: "); scanf("%d", &age); /* is a pointer */ printf("There once was a man named %s.\n", name); printf("He was %d years old.\n", age); if (strcmp(name, "MUD") == 0) { mud(); } else if (strcmp(name, "Bobby") == 0) { bobby(); } printf("%s did not like his name.\n", name); printf("%s did not like being %d years old.\n", name, age); timeFunc(); printf("He wanted to match his true self, a %s.\n", otherkin); return 0; }
Mario Rossi · 2022-01-30 06:44
>>29794 A single typo I have since fixed. I'm not going to repost the entire program
Cowboy · 2022-01-30 06:52
>>29794 More than I thought, again. #include <stdio.h> #include <stdlib.h> /* Needed for Most-Modern C */ #include <time.h> /* Library file in C dialect for calling Time in Syscall */ #include <string.h> /* Adding all these libraries feels dirty */ /* This program asks for a name, and an age, and tells the person * how old they are. WIP */ int age; char name[10]; int timeFunc() { time_t s, val = 1; struct tm* current_time; s = time(NULL); current_time = localtime(&s); printf("He was born in the year %d.\n", (current_time->tm_year +1900) - age); } void mud() { /* if (strcmp(name, "MUD") == 0) */ printf("%s wanted to be called Aloysius Devadander Abercrombie.\n", name); printf("He told me that it was short for %s.\n", name); printf("Then he told me that he was told that!\n"); printf("What a strange kind of guy who \"drinks his wine\".\n"); } void bobby() { /* if (strcmp(name, "Bobby") == 0) */ printf("He thought that %s wasn't TV ready.\n", name); printf("He thought the name Dale was better.\n"); } char otherkin[] = "My Little Pony"; int main() { printf("Enter your name: "); /* fgets(name, 10, stdin); */ scanf("%s", &name); if (strcmp(name, "Bobby") == 0 ) { printf("Damn it, %s!\n", name); } if (strcmp(name, "MUD") == 0) { printf("Your name is %s? Well, you the most borin'-ass son o' a....\n", name); } printf("Enter your age: "); scanf("%d", &age); /* is a pointer */ /* Story produces output here */ printf("\n"); /* TO FIX */ printf("There once was a man named %s.\n", name); printf("He was %d years old.\n", age); if (strcmp(name, "MUD") == 0) { mud(); } else if (strcmp(name, "Bobby") == 0) { bobby(); } printf("%s did not like his name.\n", name); printf("%s did not like being %d years old.\n", name, age); timeFunc(); printf("He wanted to match his true self, a %s.\n", otherkin); return 0; }
Marly Krushkhova · 2022-01-30 06:55
>>29796 Now that I have my simple program, I simply need to optimize. I have two instances of checking strcmp() in the program, which I can do in one. But they are very far apart from each other in the program. They are essentially in part 1 of main and part 2 of main. I must learn how I can modify my bobby() and my mud() functions in order to be able to have tem execute seperate input for part 1 and part 2. I probably should also further seperate part 1 and part 2 in the actual codepage.
Lady Jessica · 2022-01-30 06:58
>>29797 There is also the problem that when entering an age, timeFunc() fails to account for month and date. This is a minor issue, but is it possible to fix without further user input? If I attempted to, I think I would have to input two values. I think it's easier to have the user enter their full date of birth in a standardized format of my choice (I assume ISO has the easiest). This is coming along nicely, though it is a large tangent from the more complex computational programming of K&R/ANSI C, which I do hope to return to after a few more exercises.
Chan Siu Ming · 2022-01-30 07:06
>>29797 You could have a variable that keeps track of the result of strcmp C int is_muddy = strcmp(name, "MUD") == 0; // later... if(is_muddy){ >>29798 I noticed that problem too, but honestly it doesn't matter. It's not handling health care data.
Void · 2022-01-30 07:18
>>29799 Well, still closer to full optimization. What I now need to do is simply figure out if I can make those functions have unique statements that only trigger depending on where in the script they are called. If I can't, then I must think of another method for optimization. I know that this can be simplified further, though it may be beyonf my current knowledge. #include <stdio.h> #include <stdlib.h> /* Needed for Most-Modern C */ #include <time.h> /* Library file in C dialect for calling Time in Syscall */ #include <string.h> /* Adding all these libraries feels dirty */ /* This program asks for a name, and an age, and tells the person * how old they are. WIP */ int age; char name[10]; int timeFunc() { time_t s, val = 1; struct tm* current_time; s = time(NULL); current_time = localtime(&s); printf("He was born in the year %d.\n", (current_time->tm_year +1900) - age); } void mud() { printf("%s wanted to be called Aloysius Devadander Abercrombie.\n", name); printf("He told me that it was short for %s.\n", name); printf("Then he told me that he was told that!\n"); printf("What a strange kind of guy who \"drinks his wine\".\n"); printf("I asked him if he wanted to Catch the Wave, ya know.\n"); printf("Instead, all he asked for is a Pork Soda.\n"); } void bobby() { printf("He thought that %s wasn't TV ready.\n", name); printf("He thought the name Dale was better.\n"); /* Does not work because age is not yet assigned a value!!! if (age >= 25) { printf("Sadly, at the age of %s, he thought it was too late to change.\n", age); else printf("His dad would tear him a new one if he ever tried to change it though!\n"); } */ } char otherkin[] = "My Little Pony"; int main() { printf("Enter your name: "); /* fgets(name, 10, stdin); */ scanf("%s", &name); int is_muddy = strcmp(name, "MUD") == 0; int is_myPurse = strcmp(name, "Bobby") == 0; if (is_myPurse) { printf("Damn it, %s!\n", name); } if (is_muddy) { printf("Your name is %s? Well, you the most borin'-ass son o' a....\n", name); } printf("Enter your age: "); scanf("%d", &age); /* is a pointer */ /* Story produces output here */ printf("\n"); /* TO FIX */ printf("There once was a man named %s.\n", name); printf("He was %d years old.\n", age); if (is_muddy) { mud(); } else if (is_myPurse) { bobby(); } printf("%s did not like his name.\n", name); printf("%s did not like being %d years old.\n", name, age); timeFunc(); printf("He wanted to match his true self, a %s.\n", otherkin); return 0; }
Crazy Jake · 2022-01-30 07:31
>>29801 When it comes to program structure this seems somewhat similar to https://lainchan.org/inter/res/5153.html In terms of optimization it's not even close to being a bottleneck, no need to worry about optimization.
queue · 2022-01-30 08:06
>>29802 True, but I think it's probably best practice to always optimize my work before going forward, to prevent all problems. With a more complete program like this, this is the time to really start doing that. It doesn't matter if the bottleneck isn't there, if I don't pre-optimize it will be.
J.C. Denton · 2022-01-30 09:10
>>29803 My friend who reviewed my program told me that I need to watch for buffer overflow, and should always define max character input. #include <stdio.h> #include <stdlib.h> /* Needed for Most-Modern C */ #include <time.h> /* Library file in C dialect for calling Time in Syscall */ #include <string.h> /* Adding all these libraries feels dirty */ /* This program asks for a name, and an age, and tells the person * how old they are. WIP */ char name[32]; int age; int timeFunc() { time_t s, val = 1; struct tm* current_time; s = time(NULL); current_time = localtime(&s); printf("He was born in the year %d.\n", (current_time->tm_year +1900) - age); } void mud() { printf("%s wanted to be called Aloysius Devadander Abercrombie.\n", name); printf("He told me that it was short for %s.\n", name); printf("Then he told me that he was told that!\n"); printf("What a strange kind of guy who \"drinks his wine\".\n"); printf("I asked him if he wanted to Catch the Wave, ya know?\n"); printf("Instead, all he asked for is a Pork Soda.\n"); } void bobby() { printf("He thought that %s wasn't TV ready.\n", name); printf("He thought the name Dale was better.\n"); /* Does not work because age is not yet assigned a value!!! if (age >= 25) { printf("Sadly, at the age of %s, he thought it was too late to change.\n", age); else printf("His dad would tear him a new one if he ever tried to change it though!\n"); } */ } char otherkin[] = "My Little Pony"; int main() { printf("Enter your name: "); /* fgets(name, 10, stdin); */ scanf("%s", &name); int is_muddy = strcmp(name, "MUD") == 0; int is_myPurse = strcmp(name, "Bobby") == 0; if (is_myPurse) { printf("Damn it, %s!\n", name); } if (is_muddy) { printf("Your name is %s? Well, you the most borin'-ass son o' a....\n", name); } printf("Enter your age: "); scanf("%10d", &age); /* is a pointer */ /* Prevent buffer overflow */ if (age <= 0) { printf("Hello, Mr. Humonculious!\n"); return -1; } /* Story produces output here */ printf("\n"); /* TO FIX */ printf("There once was a man named %s.\n", name); printf("He was %d years old.\n", age); if (is_muddy) { mud(); } else if (is_myPurse) { bobby(); } printf("%s did not like his name.\n", name); printf("%s did not like being %d years old.\n", name, age); timeFunc(); printf("He wanted to match his true self, a %s.\n", otherkin); return 0; }
Apoc · 2022-01-30 11:44
>>29805 canf("%10d", &age); /* is a pointer */ /* Prevent buffer overflow */ if (age <= 0) { printf("Hello, Mr. Humonculious!\n"); return -1; } Isn't a buffer overflow. Thats called input validation, your checking if someone entered invalid data. scanf("%s", &name); Allows a buffer overflow. You are reading from stdin, which could have infinite characters, and writing to a 10 character buffer. fgets is the preferred solution. Since, I know how much you love standards, GNU extended the standard to allow format specifiers like "%ms" where you don't need to know the size of the buffer, libc will make one for you. #include <stdio.h> #include <stdlib.h> int main(void) { /* pointer to what buffer libc will allocate*/ char *name; /*prompt*/ printf("What is your name: "); /*The GNU extension 'm' causes libc to allocate the buffer for us - look ma no overflow */ scanf("%ms", &name); /* We use it like normal */ printf("Hello %s.\n",name); /* But must 'free()' it to prevent memory leaks - which don't matter in a prog this small */ free(name); /* This is a good safety practice, but doesn't matter in a program this small */ name = NULL; /* This is what standard says we should return, not 0 */ return EXIT_SUCCESS; }
Acid Burn · 2022-01-30 14:09
Please post complete programs in "pastebin" site, like sicp.me, or open a gitlab/sourcehut account amd put them there (much more recommended for your resume actually), then you can give us the link instead of flooding.
Special Agent Bob · 2022-01-30 14:20
>>29807 doesn't Lainchan also support .txt files in posts?
William Holtzer · 2022-01-30 16:08
>>29807 I posted like a 10 line program with comments, its a code fragment, that is intended to be discussed, not a complete work.
Special Agent Bob · 2022-01-30 18:50
>>29810 What about >>29796, >>29801, >>29805 I count a lot more than "a 10 line program with comments"
Moore · 2022-01-30 18:52
>>29810 >>29812 Which are also 4 versions of the same program.
Nameless · 2022-01-30 19:08
>>29812 Imagine posting multiple posts about the same thing and also complaining about "flooding". imo, those posts are a good posts.
Nell · 2022-01-30 19:12
>>29807 Refer to >>1 >To upload a program as a file, append .txt to the filename first. Don't use an external service to upload a program of yours, unless it can't reasonably be avoided.
Haruyoshi · 2022-01-30 19:36
>>29815 >>29812 Your also wrong. I am not OP. I was posting a 10 line code fragment to demonstrate to OP how to use a dynamically allocated buffer to avoid buffer overflows. If you were reading the thread it would be obvious because OP is using archaic syntax, depreciated functions, and vulnerable code. Honestly, what could be expected other than this learning program ANSI C having never used a typed language. Seems not helpful to have a thread about code if you can post code fragments. Including OPs entire programs which are one file, and small enough to fit on a single screen. When code starts to become multiple files or screenfuls, posting here could be annoying. I am unsure how we could have meaningful conversation about code without being able to post code fragments of about this size. It seems what your really upset about is that the thread is active compared to your preferred thread.
null · 2022-01-30 20:17
OP here. Back on a Sunny Sunday Afternoon and ready to be a Brogrammer yet again! :-) >>29806 If I use the `%m` that glib introduced does it lose compatibility with other C libraries and Compilers? Further, does it not have backwards compatibility? I think Backwards Compatibility is another best practice. So far in my realized Best Practices list I have * Readability * Optimization & Efficency * Resource Conservation * Backwards Compatibility This is a list I made myself. I do not know if there are other compiled lists of best practices (but I wholeheartedly assume there are). This list is just some of my own considerations. >>29815 >>29807 If the code exercise is now too long to post, I'm unsure what to do here. It is more than one page in my pager. I have to agree with >>29814 and >>29816 that the entire point is to upload exercises. However, it is true that this exercise is a single program with multiple uploads. I am unsure going forward. I do have a git though. As I have said repeatedly here what started this was making the Activist Shell Script, which was at >>29622. My git has also been linked, specifically my dotfile repo, at >>29678 The majority of this thread is me. I am the OP and I made it to have a C Programming Thread. This site is a shadow of its former self, and activity is incredibly low. At present the only activity in this thread is me and people commenting on my own code. That doesn't need to be though I admit I do enjoy the attention. If I begin to break a site rule by uploading these example programs which I continue to fiddle with, then I'll start fuarrrking with uploading them as attatchments or linking a git. However, for right now these excersices continue. Besides, the only reason this program is so big is repeated printf() statements. It's a basic tutorial program.
Nobody important · 2022-01-30 20:25
>>29816 >>29817 Also, please note friend that I stopped using ANSI C for a bit and began using a course on YT channel Giraffe Accademy. I do not think Giraffe Accademy is using "archaic syntax". I think that this course is good to augment my ANSI C study, but the program I have posted at >>29805 is almost entierly from that course, and is not an ANSI C challenge.
sage · 2022-01-30 20:47
>>29817 >If I use the `%m` that glib introduced does it lose compatibility The first and most important thing is that your code doesn't contain a buffer overflow. If your code contains a buffer overflow, it doesn't matter where it can run because the answer is nowhere. > with other C and Compilers? Your just calling the function 'scanf()'. Scanf is a libc standard function, and the C Standard specifies the way the function will be called. Other compilers shouldn't necessarily object to this but they may have intelligent warnings baked in to question this weird string they are passing to scanf. Nothing forbids this from working with other compilers. > with other C libraries This is the real hitch. Your using a GNU extension to the scanf() function, which means you can use other libraries with glibc, but you probably have to use glibc instead of musl , dietlibc, bionic, etc. POSIX specifies this as an optional extension. >https://pubs.opengroup.org/onlinepubs/9699919799/functions/fscanf.html > The %c, %s, and %[ conversion specifiers shall accept an optional assignment-allocation character 'm', which shall cause a memory buffer to be allocated to hold the string converted including a terminating null character. In such a case, the argument corresponding to the conversion specifier should be a reference to a pointer variable that will receive a pointer to the allocated buffer. The system shall allocate a buffer as if malloc() had been called. >Further, does it not have backwards compatibility? I think Backwards Compatibility is another best practice. Its been a GNU extension to GLIBC for a long while. BSD libc appears not to implement the extension at all.
The Fin · 2022-01-30 20:59
>>29819 I modified my program per your instruction. However, I got into some funny errors when I attempted to change age to match name. I assume that this is due to age being an integer, not a character string. Should I make an attempt to free integers like I do for character strings?
vector · 2022-01-30 21:02
>>29820 I don't know which I should do, but here's the program as a txt file. The friend said that I should use <stdint.h> which provides uint8_t. I told him that looked strage and cumbersome, and like bloat. He insisted it was correct. I did not yet implement it, and chose instead to first implement the recommended %m (which appears to do the same thing but is GNU-centric).
Hououin Kyouma · 2022-01-30 21:23
>>29821 Now attempting to add more features, such as the previously commented out region, I have produced a semantic problem where bobby() displays after executing mud() ... if (age >= 21) { printf("He only drinks the finest wine.\n"); printf("Except he hasn't turned a dime in several months...\n"); printf("Or were it years...\n"); } /* Curiouser and Curiouser. I must close the previous if */ else { printf("Except he wasn't of age, being only %s.\n", age); printf("Very critical of Temperance Laws, %s was.\n", name); } } if (is_myPurse) bobby(); { if (age >= 25) { printf("Sadly, at the age of %s, he thought it was too late to \ change.\n", age); } else { printf("His dad would tear him a new one if he ever tried to change it though!\n"); } }
t · 2022-01-30 21:26
>>29821 You are on the right track but there is an import thing to understand. "%m" only works with strings "%ms", for good reason. The reason we are interested in using %ms is to avoid a buffer overflow. A buffer overflow is where you copy more data than a place/variable/object called a "buffer" can hold into it, overwriting random other parts of memory leading to crashes, undefined behavior, and security flaws. When you copy a string, you using a buffer. However, Integers are fixed width - they have a specific known size. So you cannot 'buffer overflow' an integer. There is a phenomena known as integer overflow , but its not related to writing data to something else in memory, and overflow means something else in the context. So, because integers are a fixed size (sizeof(int)) , there is no reason to ask scanf() to allocate a buffer for the integer. The documentation ( man scanf ) says that '%m' is only valid with strings. Now, you don't have to do this. You can make a maximum size transfer like this: char buffer[128]; fgets(buffer,sizeof(buffer,stdin); This will not buffer overflow, but it also means that input can't be bigger than the fixed known size, here 128. And you 'waste' space, by allocating memory for the longest possible input, even if the input is short. These are the two allocation strategies: You can either allocate a buffer your self of fixed size, allocate a dynamic buffer which you manage resizing (more advanced), or have libc give you the right sized buffer automatically (easiest). For integers, you don't have to worry about this at all.
drop · 2022-01-30 21:26
>>29822 I fixed the strings to be %d. I noticed my mistake there almost as soon as I uploaded.
null · 2022-01-30 21:32
>>29824 I have fixed my very minor bug (put bobby() in the wrong place) and implemented the proper form of %m that >>29823 spoke of. Now I need to watch some more of the video lecture from Giraffe Accademy and see what else I can do with C to begin with.
H.R. Giger · 2022-01-30 22:04
>>29825 Little by little, every tiny feature I add shows me more. /* Doesn't work, produces negative number * printf("If %s's age was a circle, his circumfrince would be %d\n", name, (M_PI * age)); */
cdr · 2022-01-30 23:26
>>29826 Turns out the only problem with it was defining as a decimal rather than a float. All fixed. I feel very happy with having acomplished making this basic program. But I need to go farther than this now. I'm unsure if I should still continue to modify this silly little thing or if I should return to scratch for a new program.
Nemissa · 2022-01-31 00:59
... /* Part 3!!! */ printf("Enter your initial investment: "); scanf("%f", &inv); printf("Enter your investment term in years:"); scanf("%d", &term); printf("Enter your interest rate: "); scanf("%d", &rate); /* printf("Enter current rate of inflation:" ); scanf("%f", &inf); */ printf("Ok, %s. Based on the information provided, your initial investment", name); printf("of %f, what follows is your estimated earnings for the term!\n", inv); /* modified from ANSI C conversion table */ while (age <= term) { inv = (inv * rate); printf("%d\t %f\t", ++age, ++inv); /* TODO: Add current year incremented by 1 */ } } /* At present something causes a major compiler error for the below. It fails to * compile as a result */ free(name); name = NULL; return EXIT_SUCCESS; }
Molly Millions · 2022-01-31 01:07
>>29829 Still does not compile. Is still probably wrong equation too, but the syntax is the big issue here. ... printf("Ok, %s. Based on the information provided, your initial investment", name); printf("of %f, what follows is your estimated earnings for the term!\n", inv); /* modified from ANSI C conversion table */ inv = 0; while (inv <= term) { inv = (inv * rate); printf("%d\t %f\t", age, inv); = ++age; ++inv; } }
Joey · 2022-01-31 01:10
>>29830 Curiouser and Curiouser ... /* modified from ANSI C conversion table */ while (inv <= term) { inv = (inv * rate); printf("%d\t %f\t", age, inv); inv = inv + 1; age = age + 1; } } /* At present something causes a major compiler error for the below. It fails * to compile as a result */ free(name); name = NULL; return EXIT_SUCCESS; }
nibble · 2022-01-31 01:12
>>29831 Haha, extra } the whole time!! Now how do I get expected output :V
Ein · 2022-01-31 01:22
>>29832 It's getting there. I just need to figure out the right order here.
↑ · 2022-01-31 01:30
>>29833 while (/*what goes here? */ <= term) { inv = (inv * rate); printf("%d\t %f\t", age, inv); ++age; ++inv; }
Hitomi · 2022-01-31 02:16
>>29834 Still not quite right. I'm unsure if I'll get this on my own. This is my own attempt without watching a tutorial. It clearly is wrong, but the only wrong thing about it is proper syntax to be able to actually execute it. I think this goes back to my previous speculation that I may need an algebra refresher. I am a victim of Common Core Math, and as such I know very little of actual mathematic functions. Unlike many other things, I haven't really taken the time to unfuck myself in that regard (though I have learned much more than I did know over the years). /* modified from ANSI C conversion table */ while (earn <= term) { earn = (inv * (rate / 100)); printf("%d\t %f\t", age, earn); ++age; ++earn; }
Roger Pollack · 2022-01-31 03:23
>>29835 Almost there /* modified from ANSI C conversion table */ /* Thanks anon from 4g/dpt/ */ earn = (inv * (rate / 100)); while(earn <= term) { printf("%d\t %f\t", age, earn); age++; earn++; }
dictionary · 2022-01-31 21:55
After I couldn't figure out the proper method of investment, I decided to take a break and started reconfiguring a bunch of my devices, including my OSMC box. It is now monday and one of my major errands of the day has been rescheduled for tomorrow. I spent last night sleeping to the Schuman Resonance instead of a subliminal sleep tape or a full hypnosis tape, and I am now (since I awoke) listneing to 30 minute mindset some more. I think that I need to add a basic algebra refresher to this effort, and will begin studying algebra in addition to Giraffe Accademy and ANSI C and all else I'm doing. Do any lainions recommend good math books for the adult learner? >>29849 >>29850 Whoever posted this doesn't appear to be a wiggoid anyway, though may be a man. It's always increasingly hard to tell now-a-days. As for the image, I had believed that to be true. After all, I did not really understand those symbols to begin with but her explanation allowed me to know what they are (unless she's wrong, like you claim).
Ivan Petrov · 2022-02-01 00:12
>>29759 >>29760 >>29761 The problem with the "real programmer" mindset is that it puts principal over practicality. Low-level languages give you great performance and little to no overhead, but it's at the cost of significantly longer development time. Ideally, you should write in whatever language is best suited to your problem domain, while still understanding how things work at a lower level.
Yuki Nagato · 2022-02-01 00:14
>>29852 Here we go, baby https://yewtu.be/watch?v=6tuZHqcf2QA
Turing · 2022-02-01 00:35
>>29854 Most of this video thus far is soykaf I already know by heart. Good review though. I feel stupid though as I need to take an Algebra Refresher while many programmers (especially here on Lainchan) are probably at Calculus or later. The whole reason I'm doing this is that while I'm learning the language well, I am unable to perform basic math not due to invalid syntax but because I don't know the equation itself. I don't know my Times Tables by heart, but can easily do basic arethmetic. I used to avoid using a calculator in school, making pages upon pages of scratch. About a decade ago, I tried to teach myself more advanced math too (after leaving High School) and it (like C) is one of the things I was forced to put on hold. Simple Solve for X equations I would attempt to do, written-out-myself hyper-complex for my chicken scratch to equate. Example: ((2^8)*(8x^3*)*22.8+3)*12)/18=26. Solve for X. A good mental exercise. I think it's probably a good idea to start doing that again, if not on the daily. But in cases where I do know the equation, such as my most recent code sample >>29836 I think this shows a simple problem with basic Algebreic concepts, probably found in Algebra II. I do not understand how to properly do that, and got the basic equation from a book. Originally I was wrongfully trying to implement the Rule of 72 which is the next section of the financial planning book. If I have such severe problems with basic math, I worry for myself. You aren't a real programmer if you understand implementation but not the basic math involved, let alone able to persue a self-taught STEM education.
progn · 2022-02-01 01:08
>>29855 That video finished and was just review of things I already knew. I'm not sure what level of math to search for, so I'm now doing an Algebra II lesson (which is much longer) https://yewtu.be/watch?v=i6sbjtJjJ-A I have written out the thing on my whiteboard and I need to figure out how to do this.
Pulse · 2022-02-01 01:20
>>29856 I'm getting there, I already discovered I needed to add another var.
Debbie Charteris · 2022-02-01 01:26
>>29857 It is hung earn = (inv * (rate / 100)); for (inv + earn == total; ++age, ++total;); { printf("%d\t %f\t %f\t\n", age, earn, total); }
XERXES · 2022-02-01 01:30
>>29858 Still hung earn = (inv * (rate / 100)); total = (inv + earn); while (total >= inv); { printf("%d\t %f\t %f\t\n", age, earn, total); /* Possible solution: age = age + 1 but I thought that's ++age */ ++age; ++total; }
x<->y · 2022-02-01 01:35
>>29859 I fixed the algebreic inequality, tried putting another test into the machine, and found it is still hung I also just realized that I did not account for term limit, so it runs without end. Probably the reason for the hang? So how do I implement the term!?! earn = (inv * (rate / 100)); total = (inv + earn); while (earn <= inv); { printf("%d\t %f\t %f\t\n", age, earn, total); ++age; ++total; }
Chani · 2022-02-01 01:37
>>29860 Still hung. earn = (inv * (rate / 100)); total = (inv + earn); while (age <= (age * term)); { printf("%d\t %f\t %f\t\n", age, earn, total); ++age; ++total; }
nil · 2022-02-01 01:57
>>29861 I'm getting there. I've discovered yet another possibly nessesary var, last = earn * term
Nanashi No Gombe · 2022-02-01 02:11
>>29862 I am certain I will get this
Drifter · 2022-02-01 02:16
>>29863 earn = (inv * (rate / 100)); total = (inv + earn); step = (term + age); last = (earn * term); for (age <= (age <= step); total <= last;); { printf("%d\t %f\t %f\t\n", age, earn, total); ++age; ++total; }
Naomi Nascimento · 2022-02-01 02:36
>>29865 Cell phone died so no picture of my white board. This is what I currently have: E=(I*(R/100); To=(I+E); S=(T+A) L=(E*T) while (A>= S && L <= To) { printf("%d\t +%f\t %f\t", A, E, T); ++A ++T}
cond · 2022-02-01 02:41
>>29868 >>29868 Still hangs. I think what I have to do is combine a few more of these terms. This isn't C I'm struggling with, it's math. earn = (inv * (rate / 100)); total = (inv + earn); step = (term + age); last = (earn * term); while (age <= step && last <= total); { printf("%d\t %f\t %f\t\n", age, earn, total); ++age; ++total; }
Dr. X · 2022-02-01 02:49
>>29870 earn = (inv * (rate / 100)); total = (inv + earn); step = (term + age); last = (earn * term); step2 = (total + earn); while (age <= step && last <= total); { printf("%d\t %f\t %f\t\n", age, earn, total); printf("%d\t +%f\t %f\t\n", ++age, earn, ++step2); }
Agent Richard Gill · 2022-02-01 02:55
>>29871 Still hangs. Still doesn't work. I think I'm trying every possible iteration here. earn = (inv * (rate / 100)); total = (inv + earn); step = (term + age); last = (earn * term); step2 = (total + earn); while (age <= step && last <= step2); { printf("%d\t %f\t %f\t\n", age, earn, total); printf("%d\t +%f\t %f\t\n", ++age, earn, ++step2); }
synchronized · 2022-02-01 03:02
>>29872 No matter what I try to do, it hangs. earn = (inv * (rate / 100)); total = (inv + earn); step = (term + age); last = (earn * term); step2 = (total + earn); while (age <= step); { printf("%d\t +%f\t %f\n", age, earn, step2); ++age; ++step2; } earn = (inv * (rate / 100)); total = (inv + earn); step = (term + age); last = (earn * term); step2 = (total + earn); while (last <= step); { printf("%d\t +%f\t %f\n", age, earn, step2); ++age; ++step2; }
renames · 2022-02-01 03:16
>>29873 Every time I check my whiteboard I think I have it. Then I plug it in and it still hangs. earn = (inv * (rate/100)); total = (inv + earn); step = (term + age); last = (earn * term); step2 = (total + earn); while (age <= step || last <= step2); { printf("%d\t +%f\t %f\n", age, earn, step2); ++age; ++step2; }
Masami Eiri · 2022-02-01 03:49
>>29874 Do I need to add (term * inv)? Because last is only calculating total earnings for the term, wouldn't (term * inv) be grand total for investment?
Tequila · 2022-02-01 03:51
>>29875 Still hung. Is it syntax or not? earn = (inv * (rate/100)); total = (inv + earn); step = (term + age); last = (earn * term); step2 = (total + earn); grand = (total * inv); while (age <= step || last <= grand); { printf("%d\t +%f\t %f\n", age, earn, step2); ++age; ++step2; }
string · 2022-02-01 03:57
>>29876 I made another copying mistake. Still doesn't work earn = (inv * (rate/100)); total = (inv + earn); step = (term + age); last = (earn * term); step2 = (total + earn); grand = (total * term); while (age <= step || last <= grand); { printf("%d\t +%f\t %f\n", age, earn, step2); ++age; ++step2; }
string · 2022-02-01 03:58
>>29874 [I]Disclaimer: I am not going to read all your previous posts and follow your thought process, that's tl;dr[/i] It's hard to tell exactly what is going wrong. First: what do you mean by ''hangs" exactly? Is it stuck in the loop forever printing? I can see in this last example that `last` is never updated, and step2 keeps increasing. So `last <= step2` will hold true if it does before the loop starts. Second, it seems to me like you're leaving all the work outside the loop. All your loop does is print, and it prints the same value for earn each time. You need to take those updating assignments into the loop, man. Third, there ws a recent thread: >>29386 >I do think that there's a lack of understanding sometimes, I can accomplish a lot without understanding things. Trial and error until the tests pass, etc. This is essentially what you're doing, and it's not good. You need to step back and find out what is really going on, instead of just changing a line and hoping it works. We all get caught up in this sort of mental loop every now and then, but it's something we must learn to recognize and break out. You should consider training yourself in the use of a debugger. Just the basics, no need to overwhelm yourself. You will learn a lot about C (and it'll improve your current learning too), as well as about unix, which are the goals you yourself (assuming OP) stated. Third. Don't dump your whole thought process here. It's not just about IB etiquette either. It hinders your own progress, as you're dispersing a lot of energy you could focus in solving your problem. Or take a walk. Have you been drinking enough water? It's fine if you want to share your journey here (well it doesn't bother *me*), but make eaxh post a bit more meaningful. Some friendly advice, keep up the good learning.
Ivan Petrov · 2022-02-01 04:01
Latest change, I have been copying wrong as I have simplified it on the whiteboard. grand = (inv * term); >>29878 >First: what do you mean by ''hangs" exactly The program prints the first line with no additional output. >You need to take those updating assignments into the loop, man. So noted. >You need to step back and find out what is really going on, instead of just changing a line and hoping it work That's why I put this onto a whiteboard and am evaling it manually on the whiteboard. >You should consider training yourself in the use of a debugger Any good guides? > Don't dump your whole thought process here. It's not just about IB etiquette either. It hinders your own progress, as you're dispersing a lot of energy you could focus in solving your problem. I suppose so.
Pris · 2022-02-01 04:06
>>29879 Moving the vars into the while loop has not solved the problem, it still is hanging doing who knows what. I hope to get this, and I think I'll take another break. I can only stare at my whiteboard for so long.
Colmerauer · 2022-02-01 04:16
>>29881 I'll post what I have thus far before my break for all the lurkers. while (age <= step || step2 <= grand); { earn = (inv * (rate/100)); total = (inv + earn); step = (term + age); last = (earn * term); step2 = (total + earn); grand = (inv * term); printf("%d\t +%f\t %f\n", age, earn, step2); ++age; ++step2; }
Haruyoshi · 2022-02-01 04:39
>>29882 I saw my error, and took out grand and step, to prepend them in the program
Tank · 2022-02-01 04:46
>>29882 Okay, this is what I meant by step back and look at what's happening. For starters, now the variables `step` and `grand` are undefined before the loop starts. I'm surprised your compiler didn't yell at you. Are you using -Wall? Strongly recommend. Whatever they hold, it seems that the loop doesn't run at all. If it did, you'd get at least one printed statement from within. So what happens? Execution goes past the loop and into the next line: free(name). Now I look at main: int main() { printf("Enter your name: "); /* fgets(name, 10, stdin); */ scanf("%ms", &name); where's malloc()? This is likely where your code hangs. It's trying to free() something that was not malloc()'d.
Ein · 2022-02-01 04:59
>>29885 What happens with the loop? Also, remove the call to free().
cdr · 2022-02-01 04:59
>>29884 I have not yet been introduced to malloc(); and the script worked without it before the start of this third part of the script. Shortly after posting what you have put in reply, I noticed what I did and changed it to be proper. I got confused at what the other anon was telling me. My little machine is setup like this now: grand = (inv * term); step2 = (total + earn); while (age <= step || step2 <= grand); { earn = (inv * (rate/100)); total = (inv + earn); last = (earn * term); step = (term + age); printf("%d\t +%f\t %f\n", age, earn, step2); ++age; ++step2; }
Spooky · 2022-02-01 05:02
>>29886 I do not understand if I need to implement all of the vars outside or inside the loop, especially when I need step, step2, and grand as the while condition. I removed the free() and it still produces no output.
Yuki Nagato · 2022-02-01 05:13
>>29888 I went ahead and went further so I could more easily test. >tfw you thought the whole thing was just a typo because of the space between while and its conditions.... grand = (inv * term); step2 = (total + earn); step = (term + age); earn = (inv * (rate/100)); total = (inv + earn); last = (earn * term); while(age <= step || step2 <= grand); { printf("%d\t +%f\t %d\n", age, earn, step2); ++age; ++step2; printf("Initial Investment: %f\n", inv); printf("+ Total Earnings: %f\n", last); printf("--------------------\n"); printf("Grand Total: %f\n", grand); }
Kay · 2022-02-01 05:14
>>29888 Nice trips. You need to set a value before you use any variable. Otherwise, well, it'll have a value anyway, one that you don't intend it to happen. Here >>29887, grand, age, step and step2 are all used by the while loop. But you didn't define step, so god knows what's in there. You didn't define total, either, and `step2 = (total + earn);`. I suppose you need just add specofic initial values for step and step2 before the loop. I am not sure, I'm not really looking at the math, nor running the program myself. Thst's your job. Look at the expressions and think what needs to be set up before the loop, and what is to be updated at each turn. Of the variables you put inside, it seems only earn and step2 are being updated. You added grand but last is still there... what a mess.
John Doe · 2022-02-01 05:22
>>29890 Yes, I see. Still does not work. I check my math on my White Board. I check my script repeatedly. It is taking user input here. It does not run. Ity makes my computer run harder. earn = (inv * (rate/100)); total = (inv + earn); step = (term + age); step2 = (total + earn); last = (earn * term); grand = (inv * term); while(age <= step || step2 <= grand); { printf("%d\t +%f\t %d\n", age, earn, step2); ++age; ++step2; printf("Initial Investment: %f\n", inv); printf("+ Total Earnings: %f\n", last); printf("--------------------\n"); printf("Grand Total: %f\n", grand); }
Nameless · 2022-02-01 05:23
I mean, clearly you are tired, but you're also copying and pasting code from elsewhere, otherwise why would you have a free() if you don't even know what it is for? Which is bad. Don't do that. If you're going to copy and paste code, use javascript.
Bobby Newmark · 2022-02-01 05:25
>>29892 I was told to do so by another code reviewer. I did not copy/paste that. The only thing I copy/pasted was the timeFunc() and the initial version of this machine from ANSI C Second Edition.
Hiro Protagonist · 2022-02-01 05:36
>>29891 Okay I ran out of ideas. Does it print just one line and hang, prints nothing and hangs? Here's a debugging tip: add printf statements before and after the loop: printf("before\n"); while() {} printf("after\n");
Nguoi La · 2022-02-01 05:56
>>29894 It prints nothing. I think I'm grasping at straws now. I was about to add yet another var, which would be step3 = (total + earn) + earn. I think I'm gonna stop for the night before my next illgotten solution is ((total + earn) + earn) + earn
Ivan Horvat · 2022-02-01 06:35
>>29895 while conditions: s2 is less than or equal to G I = 25k R = 8% s2 = (T0 + E) s2 = (I + (I (R/100) + (I (R/100)) s2 = (25k + (25k * .08) + (25k * 0.08) s2 = (25k + 2000) + 2000 s2 = (27k) + 2000 s2 = 29,000 ++s2 = s2 + E ad infinum until while conditions met
H.R. Giger · 2022-02-01 07:06
>>29896 The entire time the failure of output was a single stray semicolin. `cc -Wall` said something about it but I ignored it not understanding it. Now I finally have output showing my math is wrong. earn = (inv * (rate/100)); total = (inv + earn); step = (term + age); step2 = (total + earn); last = (earn * term); grand = (inv * term); while(step2 <= grand) { printf("%d\t +%f\t %d\n", age, earn, step2); ++age; ++step2; } printf("Initial Investment: %f\n", inv); printf("+ Total Earnings: %f\n", last); printf("--------------------\n"); printf("Grand Total: %f\n", grand);
Cutter · 2022-02-01 07:27
>>29900 I appear to have this entire time confused the meaning of ++x. All these posts for nothing! Final one, I swear. Too much time on a wild goose chase. I learned a lot, this still does not produce expected output, but I fixed my damn output bugs and realized I had misunderstood ++s2, which I had begun to suspect but took too long to look back up. I am sorry if tonight following my progress was a disappointment. I know that a lot of people have found interest in following my own progress with learning C, but this really was a wasted night because I had a lot of misunderstandings that I did not know I had and did not make an attempt to rectify believing my only problem was math. This is only Part 3 of my little experiment program, and I've gone outside of the ANSI C coursework as well the Giraffe Accademy course. This was my own attempt at using what I already learned. I apoligize for wasting your time. I will return tomorrow and will not be posting so heavily and so often. The new code that I have for the incomplete investment machine at this time follows: /* modified from ANSI C conversion table */ /* TODO: Modify to for loop */ earn = (inv * (rate/100)); total = (inv + earn); step = (term + age); step2 = (total + earn); last = (earn * term); grand = (inv * term); while(age <= step) { printf("%d\t +%f\t %d\n", age, earn, step2); ++age; step2 = step2 + earn; } printf("Initial Investment:\t %f\n", inv); printf("+ Total Earnings:\t %f\n", last); printf("--------------------\n"); printf("Grand Total:\t %f\n", grand);
Koichiro · 2022-02-01 20:09
>>29900 >he didn't even bother look at his compiler output Sigh. One more "programmer" out in the world.
Undisclosed · 2022-02-01 22:25
>>29911 >he didn't even bother look at his compiler output Indication perhaps that compiler error messages aren't helpful enough.
Torvalds · 2022-02-01 22:30
>>29912 It was literally telling him that the block was not attached to the while loop and indented deceptively.
Mitnick · 2022-02-01 23:22
>>29913 >>29911 >>29912 A very fair point from both of you. It was my own cocksure belief that it was valid which made me overlook it. I was confused as to what exactly the compiler was saying in that -Wall. I will make sure to follow up on ALL warnings from now on, as there's a REASON behind it. As for now, I am back where I ended last night. The only problem is that E = 0, and thus s2 = 25,000 (using my example input). As such I must figure out why E != I * (R/100). I have tried making spaces and this changed nothing. I have defined the vars as follows: char *name; int age, term, step, step2, step3, rate; double inv, inf, earn, total, last, grand; I will stop posting so heavily as I had begun doing over the weekened. The weekend is over. It is unwelcome to do such large amounts of dumps regardless, but it was more welcome on the weekend because there were more active participants.
push · 2022-02-01 23:46
>>29914 >The only problem is that E = 0, >earn = (inv * (rate/100)); and >double earn; >int rate; >double inv; Well (<double> * <double> = <double> and <int> * <double> = <double>). So, Earn = INV * ? is going to give you a double like you expect. Except, Your multiplying by zero. Because (rate/100) is a <int> . Rate is an integer, and 100 is an integer. So, and integer over an integer in C gives an integer => 0. For example In C: 8/100 = 0 Compare with 8.0/100 = .08 You could fix this by changing either 100 to a double (100.0) or rate to a double.
Ender · 2022-02-01 23:59
https://gitgud.io/se7en_gitgud/c_exercise_program/ >>29915 Thank you for the information. I will begin fiddling with this soon. I did not realize this, and now understand. The big problem was spending several hours last night and the night before believing that I had a major math error. It's all just syntax, the point of learning the language.
Hiro Protagonist · 2022-02-02 00:19
>>29916 https://gitgud.io/se7en_gitgud/c_exercise_program/-/commit/dbbe51454db87a606b55ec7ab667d8cbadc8aa29 Math shows that age of 20 should be initial (other bug) and next index will be that 29,000. Each increment of +2000. However, at the age of 50, I calculate that the individual will have 750,000 (as you can see from the hard-coded output. If each increment is by 2,000, why is the age of 43 showing the final, and age 50 shows 89,000. If it is only off by one index, why is 50 a difference of 18,000, 9 times more than the expected output? Actually, all the math output is out because age 43 isn't 750,000 but 75,000. Is my White Board math wrong? Whatever the case is, something is wrong here. Back to whiteboarding!
car · 2022-02-02 00:38
>>29917 G != (T * I) G = (L + I)
Fred Nurk · 2022-02-02 02:02
>>29918 https://gitgud.io/se7en_gitgud/c_exercise_program/ I have finally fixed my math. The only problem now is that index0 of output displays +earn when I want it to be null. This is not a bug, this is an unimplemented feature.
string · 2022-02-02 06:11
>>29919 I might be working on this a bit more tonight but here is my current status. Another thing I've learned is that being self-taught means you have no one to show you the answers when you've come up with the problem yourself ^^ https://gitgud.io/se7en_gitgud/c_exercise_program/-/commit/6b99c147945dd5722693ff2acc12d636ee99f93c I've learned a lot, I have a lot more resources at my disposal now than just Giraffee Accademy and ANSI C, and I have a much better understanding of the program. I have acomplished a lot, I feel, for almost 1 week at learning this language. I feel very acomplished and hope that the next week or so lets me progress even farther. Not only have I begun to learn this but I am relearning mathematics. Do any Lanions recommend anything else to augment this? My nootropics are very good, as well as my subliminal tapes, but I'm sure there are some things that I am not doing that lanions could recommend. I'll be sure to check into >>>/drug/2 for more on the nootropics (and yes, I know of Gwern's Blog). I want to apoligize again last night for those following my progress as that was a terrible dump of useless posts which was the result of my wild goose chase. I hope that this is much better now that I actually have a working program to begin improving.
Koos van der Merwe · 2022-02-02 21:56
Replying to some older posts here as I reread the thread. >>29823 I am well aware of what a buffer and a buffer overflow is. >can hold into it, overwriting random other parts of memory leading to crashes, undefined behavior, and security flaws. I simply believed that it was too early in my learning to implement buffer overflow protection. Now that I see how simple it actually is to do, I no longer beliece that. >However, Integers are fixed width - they have a specific known size. So you cannot 'buffer overflow' an integer. Thank you for this information. As I had in my notes for ANSI-C (which I failed to recheck) an Int is a Modern Half-Register (16 Bits, 2 Bytes). >The documentation ( man scanf ) says that '%m' is only valid with strings. >You can make a maximum size transfer like this:... In my study, I see that %m is calling another C function called malloc(). malloc() tells the compiler to augment enough memory for the input and no more. However, I do not believe there is an upperlimit for malloc(), is there? So if you implement malloc() and the input is 10^10 characters long (for example) would it not implement that? At the same time defining the input with the array strategy (char buffer[128]) is bad because 1) it will only allow 128 character input, and 2) it will automatically allocate 128 character input into memory regardless of actual input. You say this in your post. The prefered behavior is obviously malloc(), but then this leads me to assume that malloc() itself has some kind of fixed size. Am I correct or incorrect? >>29915 I have also noticed that <math.h> which I called for using age as a diamiter of a circle (age * pi) changes the alias for basic declarations such as int, float, double, and other numbers. This is why the output is 0.0000000000 and so on. Is there an easy way to unset <math.h> and other headers in certain parts of the program to get default behavior?
Tank · 2022-02-02 22:17
>>29925 This says that when calling malloc() you must define max buffer. https://www.tutorialspoint.com/c_standard_library/c_function_malloc.htm Now, %m "calls malloc behind the scenes", meaning it is an alias. Attempting to find more I have found this Stack Overflow article, "What is the difference between glibc's MALLOC_CHECK_, M_CHECK_ACTION, and mcheck?" https://stackoverflow.com/questions/18153746/what-is-the-difference-between-glibcs-malloc-check-m-check-action-and-mcheck I do not know if %m is calling any of these checks or not, but it is good tangental information regardless. glib has malloc.c, which appears to have been forked by numerous people. /usr/include/malloc.h exists, but it is not implemented into my program. I do not believe this is implemented then if malloc.h isn't a header defined, and a default malloc() is then called, unmodified from standard. This is quite an indepth research project for just two characters in a larger program. I still don't have the answers I'm seeking.
Tequila · 2022-02-02 22:33
>>29926 I find a large number of articles with a simple Wikipedia search query https://wikiless.org/wiki/Special:Search?search=malloc%28%29 A lot of them are very good for my studies. https://wikiless.org/wiki/C_dynamic_memory_allocation?lang=en https://wikiless.org/wiki/Memory_pool?lang=en https://wikiless.org/wiki/Assertion_(software_development)?lang=en https://wikiless.org/wiki/Stack-based_memory_allocation?lang=en According to these articles, malloc() is defined in <stdlib.h>. I find in there extern void *malloc (size_t __size) __THROW __attribute_malloc__ ... and a large number of other references. >malloc() does not initialize the memory allocated, while calloc() guarantees that all bytes of the allocated memory block have been initialized to 0. >int *array = malloc(10 * sizeof(int)); >This computes the number of bytes that ten integers occupy in memory, then requests that many bytes from malloc and assigns the result to a pointer named array (due to C syntax, pointers and arrays can be used interchangeably in some situations). After reading this, my assumption is that %m calls malloc() to be the default size of int if it is not otherwise defined. >The GNU C library (glibc) is derived from Wolfram Gloger's ptmalloc ("pthreads malloc"), a fork of dlmalloc with threading-related improvements The article then goes into providing very technical information on how dlmalloc works. But again, is this not only referencing the use of <malloc.h>? >Theoretically, the largest number should be the maximum value that can be held in a size_t type, which is an implementation-dependent unsigned integer representing the size of an area of memory. In the C99 standard and later, it is available as the SIZE_MAX constant from <stdint.h>. >On glibc systems, the largest possible memory block malloc can allocate is only half this size, namely 2^(CHAR_BIT * sizeof(ptrdiff_t) - 1) - 1. /usr/include/stdint.h -> # define SIZE_MAX (18446744073709551615UL) # else # if __WORDSIZE32_SIZE_ULONG # define SIZE_MAX (4294967295UL) # else # define SIZE_MAX (4294967295U) # endif # endif My program also does not call <stdint.h> unless these are references in one of the other headers I use. So what the hell is %m /actually doing/?!?
Project 2501 · 2022-02-02 22:55
>>29927 Also from /usr/include/stdlib.h /* Get size_t, wchar_t and NULL from <stddef.h>. */ #define __need_size_t #define __need_wchar_t #define __need_NULL #include <stddef.h> I look up /usr/include/stddef.h /usr/include/stddef.h: No such file or directory What kind if a clusterfuck of libraries is this soykaf? Wikipedia redirects stddef.h to https://wikiless.org/wiki/C_data_types?lang=en >The C language specification includes the typedefs size_t and ptrdiff_t to represent memory-related quantities. Their size is defined according to the target processor's arithmetic capabilities, not the memory capabilities, such as available address space. Both of these types are defined in the <stddef.h> header (cstddef in C++). >size_t is an unsigned integer type used to represent the size of any object (including arrays) in the particular implementation. The operator sizeof yields a value of the type size_t. The maximum size of size_t is provided via SIZE_MAX, a macro constant which is defined in the <stdint.h> header (cstdint header in C++). size_t is guaranteed to be at least 16 bits wide. Additionally, POSIX includes ssize_t, which is a signed integer type of the same width as size_t. Self-Referencial Libraries are the only way I understand this working, but if there are references to non-existant header files in glibc then how does it work? Is it a GNU/Bug? I have found SIZE_MAX in <stdint.h> but it's not implemented. I have found many references to malloc() which appear to reference other libraries. How do I untangle this web? https://wikiless.org/wiki/Printf_format_string?lang=en#Flags_field doesn't even mention %m.
cond · 2022-02-02 23:28
>>29928 This is also explained in the manpage for malloc(3) with a reference to feature_test_macros(7) which is glibc specific. malloc(3) is saying everything I have already seen. It also says that malloc() conforms to POSIX.1-2001, POSIX.1-2008, C89, and C99. >By default, Linux follows an optimistic memory allocation strategy. This means that when malloc() returns non-NULL there is no guarantee that the memory really is available. In case it turns out that the system is out of memory, one or more processes will be killed by the OOM killer. For more information, see the description of /proc/sys/vm/overcommit_memory and /proc/sys/vm/oom_adj in proc(5), and the Linux kernel source file Documentation/vm/overcommit-account‐ing.rst. > Normally, malloc() allocates memory from the heap, and adjusts the size of the heap as required, using sbrk(2) [...] sbrk(2) is aliased to brk(2). > brk() and sbrk() change the location of the program break, which defines the end of the process's data segment (i.e., the program break is the first location after the end of the uninitialized data segment). Increasing the program break has the effect of allocating memory to the process; decreasing the break deallocates memory. > C library/kernel differences >The return value described above for brk() is the behavior provided by the glibc wrapper function for the Linux brk() system call. (On most other implementations, the return value from brk() is the same; this return value was also specified in SUSv2.) However, the actual Linux system call returns the new program break on success. On failure, the system call returns the current break. The glibc wrapper function does same work (i.e., checks whether the new break is less than addr) to provide the 0 and -1 return values described above. feature_test_macros(7) This is completely irrelevant to what I am trying to understand. printf(1) and printf(1POSIX) are the wrong manpages. However printf(3) is the right one. > Field width > An optional decimal digit string (with nonzero first digit) specifying a minimum field width. If the converted value has fewer characters than the field width, it will be padded with spaces on the left (or right, if the left-adjustment flag has been given). Instead of a decimal digit string one may write "*" or "*m$" (for some decimal integer m) to specify that the field width is given in the next argument, or in the m-th argument, respectively, which must be of type int. A negative field width is taken as a '-' flag followed by a positive field width. In no case does a nonexistent or small field width cause truncation of a field; if the result of a conversion is wider than the field width, the field is expanded to contain the conversion result. I don't think this is what I have done here with %m. printf(3POSIX) is a single page, referencing fprintf. fprintf(3POSIX). After reading all these manuals and finding the only reference to "m" being a definition of length, I have to assume that where I put %m, the executed program takes input and allocates memory only when it is inputed. The maximum size of %m is defined somewhere in the standard C library. How that is defined is somewhat confusing because reading the actual header files in glibc is confusing, and includes references to other header files, some of which do not exist. Now my question is, if malloc() max-length is predefined in the library, and %m is defining a memory allocation length based on the length of a var (upto SIZE_MAX), how does the program know to not yet implement SIZE_MAX if the var is user input, and yet undefined? This is probably something on the microprocesser level.
stack · 2022-02-03 00:16
>>29929 I wrote out a lot of further analysis quoting scanf(3), fscanf(3POSIX), and other things (many of which were already quoted in the thread. it has been lost to cyberspace. My point was that by studying this simple flag, I now know what %m does, I now know what malloc() does, and I now know more about C Memory Allocation (but not yet to the Microprocesser level).
Linda Lee · 2022-02-03 02:39
>>29931 I haven't programmed much today. I don't think I can every day. I have other things I must do. What I did today that was programming related was study this. At present time the program is unmodified. I may work on it later tonight but after cleaning my house I am rather beat. I hope that the lurkers can contribute to my posted notes on malloc() so I can know more about it myself.
t · 2022-02-03 16:51
>>29688 Forgot to mention that 21st Century C, 2nd ed. covers almost all of the tools listed in that post. >>29916 >https://gitgud.io/se7en_gitgud/c_exercise_program/-/blob/master/program.c#L55 - pls add a license such as Creative Commons Zero: https://creativecommons.org/publicdomain/zero/1.0/ (don't use Public Domain because it may not exist in all countries) - It's best to keep integers such as age unsigned if they can't (or shouldn't) be negative. It's makes the code more correct and self-documenting. - Switch scanf() to fgets() when you get string input (fgets() checks the bounds, which makes it secure). Also never use gets(). C++ made everything that is related to strings much easier and much more pleasant. I guess using C-style C++ is an acceptable option? Also, 21st Century C, 2nd ed. has some goods tips on string handling. - Move all function prototypes and data structures to a header file. Do use include guards: http://www.cs.kent.edu/~nmadi/CS2/Notes/include_guard.html or http://faculty.cs.niu.edu/~mcmahon/CS241/c241man/node90.html (i.e. put your header files inside the #ifdef) - If you build a debug build, compile with at least -Wall -Wextra -Og -g -g3 options. (perhaps also use -pedantic and -Wformat-security or -Wformat=2) - N.B. Sometimes changing compiler optimization options can unearth a bug in your code (perhaps even undefined behavior) - Start using makefiles: Here is a makefile tutorial: https://www.cs.colby.edu/maxwell/courses/tutorials/maketutor/ or https://makefiletutorial.com
Unnamed · 2022-02-03 19:13
Good day, lains. Since this is a C thread, I'm looking for the K&R C book, but the 1st edition(yes, the 1st edition) and that has a good quality? The ones in libgen(both pdf and djvu) and archive.org are not good. inb4 "use the ANSI version" I'm programming on MSX and it uses the K&R C version, before the ANSI was even a thing, so I do need the K&R C 1st Edition to check things when I'm unsure of something. The internet will not help as much since any search site will return C80 or whatever searches.
J.C. Denton · 2022-02-03 21:03
>>29936 I'll make it CC0, yeah. It's probably a good idea. I'll look more into fgets. I initially made the script use fgets and commented it out because another code reviewer told me that was wrong and to use scanf. I am getting a lot of contradictory things from different places. >It's best to keep integers such as age unsigned[...] I have noted this as well and will implement. Looking up specifically how to do that it appears I literally put the word "unsigned" before the int declaration. https://www.educba.com/unsigned-int-in-c/ >Move all function prototypes and data structures to a header file. >[...] >Use makefiles I know what these are, and I understand its concept, but for this exercise program I do not yet see the point into making it a bunch of little linked files. When I move on from this and am happy with all the program can do I will do so, but for now a single file with all of the code is fine for me I think. I will move to that design model later. As for my compiler's extra flags, I already learned what -Wall is but all these other flags I don't know anything about and will look up. I might alias cc to have these extra flags. >>29937 The one I got off of Archive was fine. What you're probably looking for is one that is a clean made-for-digital format. K&R 2nd Edition (ANSI C) has an actual formatted PDF/ePUB because it was republished as one later on. K&R C 1st Edition was never republished in a digital format so all you have are scans of it. You could always take that scan, OCR it, and make your own ePub though! If you did, be sure to distribute it.
J.C. Denton · 2022-02-03 21:16
>>29938 >>29936 Looking further into fgets() I see that the proper syntax is: char *fgets(char *str, int n, FILE *stream) In such a case, the int n is the maxiumum character entry. fgets() thus requires a static limit for this, and appears to undo malloc() which I had looked into prior. I do not believe that fgets() and malloc() are compatible. I have pushed the program to now have unsigned ints. I did not unsign doubles, I am unsure if it is nessesary. I am reconsidering my position on turning it into a linked program using makefiles as I look at my codepage since it is getting rather long. I just thought it might have been too early. https://gitgud.io/se7en_gitgud/c_exercise_program/-/commit/143eb91268d2c8a5c759159db6204b3dd15a287d If I do have basic semantic problems it's probably best for me to learn what they are and fix them before I begin to implement more features, such as I was planning to already do for my investment calculator (which I can proudly say is my first "real" C Program, only a week after beginning the language).
Agent Smith · 2022-02-03 21:33
>>29936 Found this now. https://github.com/b09/c_resources
renames · 2022-02-03 21:35
>>29940 And a currated list https://github.com/b09/awesome-programming-books https://github.com/zv/awesome-programming-books
Koos van der Merwe · 2022-02-03 22:41
>>29941 lel. This is an Anti-Purist book, an Anti-Me book, an Anti-Fuddy-Duddy book.
overriding · 2022-02-04 00:52
>>29943 The entire first chapter pushes that using `cc program.c` is crap and everyone uses Makefiles (or CMAKE flags) now. I don't know how I feel about this. It goes on to say that glib has invented an all-libraries header called glib.h, and you can also make an all-libraries header by linking your own header file containing a list of nessesary libraries. Also, using a header makes the program that many more lines long, so my program is actually the program plus the entirety of the libraries once compiled. I don't know how I feel about that. Is it really best practice to have a million little files with the main.c being only 3-6 lines long? That sounds like one of the things that the millenial dumbshit has made standard behavior.
Arisu Mizuki · 2022-02-04 01:58
>>29948 > `cc program.c` is crap and everyone uses Makefiles (or CMAKE flags) now. Correct. CMake is especially popular with C++. > Is it really best practice to have a million little files Not a million, but a bunch of medium sized files with each file containing related functions. Header files containing function prototypes and data structures, regular .c containing the implementations.
Zuse · 2022-02-04 02:20
>>29949 The Cat -v Institute says that in place of GNU autoconf/automake, CMake, imake, scons, waf, you should use mk, or plain old portable makefiles. They also state that GCC has a lot of problems too: https://harmful.cat-v.org/software/GCC Are you trying to say Uriel wasn't right?
Case · 2022-02-04 03:13
>>29786 >very curious how <time.h> worked in the first place as I believe the use of external libraries should be avoided at all costs, for a purer language Time.h is part of the C standard library. It's not an external library. You are also wrong in thinking like that, the worthiness of a language is based on how many libraries it has, since that is an indication that the language is used a lot by many people for many reasons. The C standard library is also quite limited and so you are forced to use external library. If you don't believe me, see how far you can go without posix library or even graphical ones.
() · 2022-02-04 03:33
>>29835 Read Lang's Basic Mathematics on the side. It will fix your weak mathematics. The book covers from nothing up to high school algebra. That is good enough for now. You can decide if you want to learn undergrad level mathematics later, but it's always good to know your high school mathematics well enough.
Lady Jessica · 2022-02-04 03:40
>>29953 Thank you. I am very happy to be recieving these tips. As I have said I never had the oppertunity to go to college, but I still may have the chance. https://libgen.fun/book/index.php?md5=576728B662199BC472C74DCBE12D3E5C I have many books now, and probably should start reading them before I ask for even more resources.
Joey · 2022-02-04 03:42
>>29884 On malloc, read this: >>29806
Unidentified · 2022-02-04 03:47
>>29914 >I will make sure to follow up on ALL warnings from now on, as there's a REASON behind it. Always fix the first error, most of them follow from the first one. So when you receive all the erros from the compile, start fixing them from the top. Fix one, compile, if still has any error, repeat. Untill you can recognize that some errors are related to previous one and so you can fix most of the
progn · 2022-02-04 07:13
Is K&R 2nd Edition's longest line(10.9) code wrong? for example, if the input line is 999 characters and if it's 998 characters long, the program thinks they're equal in length
Agent Richard Gill · 2022-02-04 11:24
One way to handle user input in C is to use fgets() to get a line of input and then scan it a la scanf(). Also remember to limit output when using scanf() See p. 130 of C Primer Plus. Chapter 8 of C Primer Plus is focused on getting input from the user. >https://gitgud.io/se7en_gitgud/c_exercise_program/-/blob/master/program.c#L51 Age could also be an unsigned short int or another type: https://en.cppreference.com/w/c/types/integer >https://gitgud.io/se7en_gitgud/c_exercise_program/-/blob/master/program.c#L58 Switch printf() to puts() when you don't need to output a formatted string. >>29938 >I'll make it CC0, yeah Remember to at least put the license text as a comment in all source code files (or at least a comment at the top of all files that states that the code is released under CC0 and you can view the license text at $address)
Tequila · 2022-02-04 15:45
typeof is now part of the standard https://nitter.net/__phantomderp/status/1489308969940172807#m
Acid Burn · 2022-02-04 18:01
>>29959 Nice, it'll help for those dark magic macros.
quote · 2022-02-05 10:18
>>29958 I will look at the relevant chapters in your book. However, as you see in the thread I comment on using fgets repeatedly, which is very confusing. I have also talked about %m after learning it, which led to a study on malloc() and C Memory Management. I don't see the point of defining width with integer types. This looks like needless definitions added to C99. Why not keep with the simple one-word classifications, like in the K&R book? Thank you for the advice on puts(). I read POSIX-2017 definition. printf() only if you're classifying a var, while puts is essentially pure echo.
list · 2022-02-05 16:39
>>29969 >fgets Use getline/getdelim on POSIX. > I don't see the point of defining width with integer types Networking exists, where you want types to have the same width at both ends of the line. To be honest, variable width integer types (baring size_t) is one of the worst mistakes of C.
Lunch · 2022-02-05 20:54
>>29970 >Description: The getdelim() function shall read from stream until it encounters a character matching the delimiter character. The delimiter argument is an int, the value of which the application shall ensure is a character representable as an unsigned char of equal value that terminates the read process. If the delimiter argument has any other value, the behavior is undefined. >Rationale: These functions are widely used to solve the problem that the fgets() function has with long lines. THe functions automatically enlarge the target buffers if needed. These are especially useful since they reduce code needed for applications. -- getdelim(3POSIX) from POSIX-2017. >Description: The fgets() function shall read bytes from stream into the array pointed to by s until n-1 bytes are read, or a <newline> is read and transferred to s, or an end-of-file condition is encountered. A null byte shall be written immediately after the last byte read into the array. If the end-of-file condition is encountered before any bytes are read, the contents of the array pointed to by s shall not be changed. >The fgets() function may mark the last data access timestamp of the file associated with stream for update. The last data access timestamp shall be marked for update by the first successful execution of fgetc(), fgets(), fread(), fscanf(), getc(), getchar(), getdelim(), getline(), gets(), or scanf() using stream that returns data not supplied by a prior call to ungetc(). -- fgets(3POSIX) from POSIX-2017 >Description: The fscanf() function shall read from the named input stream. The scanf() function shall read from the standard input stream stdin. The sscanf() function shall read from the string s. Each function reads bytes, interprets them according to a format, and stores the results in its arguments. Each expects, as arguments, a control string format described below, and a set of pointer arguments indicating where the converted input should be stored. The result is undefined if there are insufficient arguments for the format. If the format is exhausted while arguments remain, the excess arguments shall be evaluated but otherwise ignored. >Rationale: This function is aligned with the ISO/IEC 9899:1999 standard, and in doing so a few ``obvious'' things were not included. Specifically, the set of characters allowed in a scanset is limited to single-byte characters. In other similar places, multi-byte characters have been permitted, but for alignment with the ISO/IEC 9899:1999 standard, it has not been done here. Applications needing this could use the corresponding wide-character functions to achieve the desired results. -- fscanf(3POSIX) from POSIX-2017
() · 2022-02-05 21:01
>>29973 There's also gets(). Quite a way to complicate things, yes? All these redundant features for the slightest difference in usecase. Now I know why the respected experts and elders hated C99 and most before it.
Masami Eiri · 2022-02-06 10:58
>>29974 > gets() it's insecure, do not ever use it.
Haruyoshi · 2022-02-07 01:00
>>29978 As I saw. The problem with it appears to be that it keeps input in memory, never freeing it. This is an obvious security concern. The Linux Programmer's Manual says "Don't ever use gets()" and the POSIX-2017 Specification says "This may be removed in a future revision."
Rick Deckard · 2022-02-07 04:00
>>29974 C should be respected, but it was created from innocent minds. C99 tried to fix a lot of very common security errors. People, including programmers, hate to be told they are wrong which explains the backlash.
Undisclosed · 2022-02-07 10:21
>>29991 >C99 >People, including programmers, hate to be told they are wrong which explains the backlash. There is no backlash against C99. C99 is often the standard that people aim for but mostly because C11 is too 'new' rather than broken, and they see no need to leverage new C11 features for portability. There is sometimes a backlash against compiler writers. This has nothing to do with C89 vs C99 vs C11.
Tyrell Wellick · 2022-02-07 12:31
C11 among others introduce stuff that is best served on OS level, not on C level.
Shogun · 2022-02-08 11:55
>>29990 Not only that, but gets() never checks the bounds which means that it it is a security nightmare. When you get input in C, you must check that it fits the destination. This is why you should not ever use gets(), use fgets() instead. Read Smashing The Stack For Fun And Profit: https://insecure.org/stf/smashstack.html and p. 119 (§ 0x320) and pp. 167~193 and p. 419 from Hacking: The Art of Exploitation, 2nd edition by Jon Erickson. Read Hacking: The Art of Exploitation, 2nd edition by Jon Erickson and Programming Pearls, 2nd edition by Jon Bentley at some point.
Tomohisa "Tom" Kanezaki · 2022-02-08 12:01
>>30006 The problem with K&R is that it never explains this kind of stuff nor does it cover newer standards (most importantly C99). For this reason, I actually prefer C Primer Plus, 6th edition by Prata over K&R.
The Phantom Phreak · 2022-02-09 08:54
>>29650 >GO a successor of C I'm trying to figure out what supposedly is making GO a successor of C since like 2010. It might be a lang for quickly putting together some parallel server demon on some massive server by someone very fresh to programming. But other than that I barely see it's uses. For kernel level programming it's too high level in sense it comes with massive bloat, unless you target to use code monkeys to do that job. In that case bondage and discipline it introduces might have a point. Otherwise it's just meh. Writing text editors? Maybe, but you can do the same in C if you are experienced in C and it would work faster. IMHO there is a little appeal in switching to GO if you are already a seasoned C programmer. If you are a programming newbie GO might be potentially not bad start especially considering the fact that it is about the only serious and usable not objectly oriented quite high level programming language that is around. Years ago that newbie intoductionary language niche was filled by Pascal. Getting introduced to programming by an OOP language is a guarantee of a severe brain damage known as belief in foogazi "OOP principles" and generally distracts newbie by forcing them to dable with concept of a class - concept that makes no sense to most tree digits IQ individuals but OOP programers are fooing themselves into believig it's a very wise and enlightened concept.
Jet Black · 2022-02-09 13:14
>>30031 I'm trying to figure out what supposedly is making GO a successor of C since like 2010. It's a successor in that it came afterwards and takes a lot from it. It's not a C replacement, because it's not a systems programming language. >It might be a lang for quickly putting together some parallel server demon on some massive server by someone very fresh to programming. But other than that I barely see it's use. It's a simple language with a garbage collector. There's not really any other language like that. It's useful for anything where you want a simple language with a garbage collector, which is quite a lot, really. >For kernel level programming it's too high level in sense it comes with massive bloat, unless you target to use code monkeys to do that job. In that case bondage and discipline it introduces might have a point. Otherwise it's just meh. This sounds completely deranged, and no one would advocate using go for kernel programming. >Writing text editors? Maybe, but you can do the same in C if you are experienced in C and it would work faster. As long as a text editor can keep up with the input of the user, and isn't gratuitously slow, it doesn't really matter how fast a text editor is. >IMHO there is a little appeal in switching to GO if you are already a seasoned C programmer. Depends what you're writing. It's usually faster to write and debug a go program than a C program. >If you are a programming newbie GO might be potentially not bad start especially considering the fact that it is about the only serious and usable not objectly oriented quite high level programming language that is around. This is probably true actually. These's definitely a hurdle of learning "a language" when people start programming, and acquiring the implicit knowledge people have about how something works is kind of hard. Then again, I don't really know what newbies are like. I just know I didn't really find anything good when I was learning to program.
Anonymous · 2022-02-10 01:02
Well, I spent a week on this and got far. Now I need to go even farther. It's been a few weeks since I last picked up a book and tried to program. I think I'll do it again. As it is now, my latest program is an investment calculator. What I want to do is add more financial features, and produce graphs and charts plotting the output. A purely basic program that any adept should be able to produce.
Dox · 2022-02-10 06:24
>>30031 >IMHO there is a little appeal in switching to GO if you are already a seasoned C programmer. Go was created by seasoned C programmers. The thing with C, and it's something I suspect a lot of hardcore C fanatics don't run into because they don't write software where it's an issue, is that it scales up poorly. It's a fantastic systems language, but as you start reaching higher levels its pros start to fade away and its cons become less justified. For something like, say, an imageboard engine, the security, reliability, quick turnaround time, and ease of debugging that you get from a stricter, higher-level GC'd language like Go are more than worth the speed boost you'd get from C.
progn · 2022-02-10 16:27
>>30031 >I'm trying to figure out what supposedly is making GO a successor of C It's not a real successor. It's just way to get C/C++ programmers to try out Golang.
Nobody important · 2022-02-10 20:22
>>30052 >Go was created by seasoned C programmers. No shіt Sherlock. >>30035 >This sounds completely deranged, and no one would advocate using go for kernel programming. Your mother sounds deranged https://www.usenix.org/system/files/osdi18-cutler.pdf
Hitomi · 2022-02-11 00:57
Looking into how to expand my program, I thought the next thing I should try is plotting the output of the investment. It appears that most sites recommend an addon library called GNUPlot. Is there not an integrated library or a standard practice for producing charts and graphs in C itself?
Pulse · 2022-02-11 01:18
>>30069 It looks like it doesn't. Does COBOL? https://www.edaboard.com/threads/can-c-programming-plot-a-graph.138764/ The 'standard c' language does not have graphing functions. This will also be very dependent on the operating system or device that will display the graph. This kind of functionality will normally be provided as an additional library or API call depending on the compiler / operating system. I suggest that you provide more details regarding Operating system / compiler / cpu etc. With 'c' you can always write your own or perhaps find something already written on the net According to https://bigprof.com/c4engineering/graph01.htm you can, but this method is entierly dependent on screen coordinates, the oppisite of best practice and something not done since the 1970's and early 1980's. So, if I wish to produce a chart of my investment outcome I either have to make the chart myself using hacky methods such as https://www.programmingsimplified.com/c/program/draw-bar-chart or using an external program such as GNUPlot. I however was trying to avoid graphics and wanted the output to appear in the terminal
Apoc · 2022-02-11 01:30
>>30071 Once again, UNIX saves the day. There is a UNIX utility called graph(1) https://en.wikipedia.org/wiki/Graph_(Unix) https://en.wikipedia.org/wiki/Plotutils Why aren't these UNIXv7 utilities implemented into POSIX?
Moore · 2022-02-11 01:35
>>30072 GNU Provides a guide for implementing its version of graph(1) via plotutils(1) into C via the libplot library, with example programs as early as 1972! https://www.gnu.org/software/plotutils/manual/en/html_node/C-Programming.html I will spend a few hours bit reading how to use this, then implement it into my own program. It looks rather straight-forward.
Iverson · 2022-02-11 02:47
>>30073 https://gitgud.io/se7en_gitgud/c_exercise_program
list · 2022-02-11 06:27
>>30078 Another change before I actually try to make the plotter.
Cowboy · 2022-02-11 11:23
>>30078 * insert standard rant about n00bs using strcmp instead of strncmp *
J.C. Denton · 2022-02-11 11:27
>>30072 you can just use gnuplot with sixel or regis support or asci art output.
Lukasiewicz · 2022-02-11 19:06
>>30079 Why do you use such a hideous font? Sure it looks like old skool, but it is actually hard to read.
HELIOS · 2022-02-11 19:58
>>30086 it seems to be a default xterm font
Moore · 2022-02-11 22:33
>>30084 Gay. Though, there may be a better graphical library than libplot, which appears to be completely unused. Looking for examples for libplot I find gnuplot code. Looking for examples for C Graphics I find Indians who believe TurboC is C and all use the <graphics.h> library asuming this to be standard. It is quite interesting to me how the simple production of a line graph to chart the output of my investment calculator has brought me to this elevated point. >>30083 So strncmp() limits the size as opposed to strcmp() which does the same thing but is unlimited? So noted. >>30086 >>30087 It is default. You can find more configurations in my dotfile repository. It is not unreadable to me, nor hideous.
Roy Batty · 2022-02-12 08:44
>>30091 I don't know about gnuplot, but I have used a similar technique of printf-ing output to feed into graphviz. It works great with small programs.
hash table · 2022-02-12 10:10
Here is a concice and to the point review course I have found on YouTube in lue of me programming as of late. https://www.youtube.com/watch?v=_X4ejt-XblM I need to implemnt this line graph, then I can move forward. I simply want to plot the output of the investment calculator. If I continue this program, I wonder if I could sell copies. I might change the license to GPL v3 if I did that. Keep watch. I have to wonder if making the leap to a graphics library is too much of a leap. This began because I wanted to print out a line graph in C. Maybe I could just use the Curses library instead. I do not know, I do not have much experience programming in Curses. I do have experience using the C*Music Player though (hah). Maybe I should expand the program to have more investment features before I begin plotting. The thing is, people have been using computers to generate standard charts outputted to terminal since the 1970's. Even if there isn't a standard way to do this, I would expect to be able to find more ready-made examples. I am finding squat. I'm finding even less about this libplot API I found. Most results return with gnuplot instructions. I probably will just settle for that. All I want is a simple line graph showing the numbers that already return on a simple X,Y axis. Of course, once I learn to do this I can produce bargraphs, picharts, and much more. >>29715 Rereading the thread I meant Micosoft BASIC 7, not Microsoft BASIC 8. There is no such thing. I have also had some experience with Apple BASIC.
progn · 2022-02-12 12:22
>>30087 Of course it is, but what prevents you from using some modern replacement like Source Code Pro?
Von Neumann · 2022-02-12 22:13
>>30097 >>30097 Because that is grotesque. You care more about font than the content.
list · 2022-02-13 02:19
>>30102 To be fair, in his case, if the font makes it hard to read, he can't care about the content since he is having problem trying to read it. >>30096 I used SDL to plot graphs. Thought I had to make my axis, etc. I only used SDL for graphics(window and pixel manipulation).
William Holtzer · 2022-02-13 02:22
>>30104 >>30096 Also, Bjarne's Programming: Principles and Practice Using C++ book has some chapters on graphs(13-16) and you could use that to make a nice graph library with just SDL. It's in C++, but you can easily take what you need from his explanation.
ay(t) · 2022-02-15 01:04
thank you for something to keep occupied with while stuck at a hospital , monitoring me for panic attacks or smt .
Random · 2022-02-19 20:12
oh god who made this https://github.com/catsmells/emojiC/
roll · 2022-02-19 23:14
>>30185 You did then you linked it.
Shogun · 2022-02-20 03:59
>>30185 That's just a pile of defines. Good esolangs completely change the semantics, not just syntax. See https://gitlab.com/femsf/c-plus-equality
Johnny · 2022-03-05 16:36
Good day lainons, I'm trying to learn data structures in C, do you have any recommendations? I had intended to use this https://www.amazon.com/Data-Structures-C-Noel-Kalicharan/dp/1438253273, but I couldn't find it on libgen.
Bobby Newmark · 2022-03-05 16:49
>>30308 Just get a decent data-structures/algorithms book, like Introduction to Algorithms (CLRS). Also, watch MIT opencourseware algorithms and data structures videos.
Johnny · 2022-03-05 18:22
I didn't know Introduction to Algorithms covered data structures, thanks; however, I was hoping for something that also covers implementations in C, which is why I picked the book mentioned above; if there is a good reference on implementations, it would be very helpful, and thank you again.
car · 2022-03-06 03:25
>>30308 get skiena's The Algorithm Design Manual. more about practical problem solving than a theoretic/proof approach. letctures are online https://www3.cs.stonybrook.edu/~skiena/373/videos/
Ivan Horvat · 2022-03-07 21:09
>>30052 >C doesnt scale because its full of script kiddie soykaf like unclean macros, and no proper way to do imports. theres literally nothing more to it than that. i found this out when i was 15. so no, this isn't a question of just "not bumping into the issue"
Crash Override · 2022-03-14 23:14
>>30007 So does C Primer Plus teach you bad habits, or is it "modern" in the sense that it teaches you best practices and good habits from the get go?
Neuromancer · 2022-03-14 23:34
>>30413 > Is C Primer Plus "modern" in the sense that it teaches you best practices and good habits from the get go? Yes*. C Primer Plus is, in my opinion, the best book that teaches C programming. It's also more suitable for a beginner AND the book goes into more advanced topics as well. *But the reality is more complicated... There are also some OS and POSIX specific functions that can be better, however. For example, OpenBSD (and later FreeBSD) have a function called strlcpy() that is also secure but it can be better/easier than strncpy(), see https://man.openbsd.org/strlcpy.3 For POSIX stuff, you really want to read Advanced Programming in the Unix Environment. Also, see >>29688 (especially https://suckless.org/coding_style/ and the article series on undefined behavior)
Jim Hilger · 2022-03-15 13:54
Are there any minimal terminal emulators written in sdl? I want to see how user input and rendering works but I am new to C. I tried looking at st which directly uses X11 but I don't understand most of it
Six · 2022-03-15 16:59
>>30418 >Are there any minimal terminal emulators written in sdl? Not that I know of. However, using SDL, wxWidgets, FLTK and QT are much better than using X11 directly. But you should be somewhat familiar (but not much, just a high-level overview) with X11 and Xlib/XCB. >I want to see how user input and rendering works but I am new to C. Terminal emulators can be much more complex than one might think at first. There is an video series on making a terminal emulator: https://www.youtube.com/watch?v=9e38ORrkbtc&list=PLzLzYGEbdY5nKCfUgfk8tCO9veao_P1fV&index=1 Since you are new to C, you should write simpler programs at first. >st st is probably the simplest terminal emulator out there. X11 is notoriously ugly, however. I encourage you to continue studying and tinkering with the st source. There are also 2 books The X Window System: Programming and Applications with Xt, OSF/Motif, 2nd edition by Douglas A. Young and The Joy of X (not the math book) by Niall Mansfield. Joy of X provides high level overview of X11 and The X Window System: Programming and Applications with Xt, OSF/Motif, 2nd ed. is about programming. Again, I don't recommend actually using Xlib or XCB.
John Rain · 2022-03-15 23:59
>>30418 Do you want a terminal emulator example or just a simple SDL example program? Terminal emulators have a lot of baggage, they're more complicated than a notepad program. A simple SDL text editor may be a better place to start.
aliased · 2022-03-16 03:13
>>30419 >>30422 Thanks for this! Gave me a clear idea.
Dr. X · 2022-03-16 09:12
>>29649 Ok, but why is the program behaviour different from what's in the source code on your screen? Fahrenheit is spelt correctly in the program output, but not in the window you have the source code open in. Secondly, in the source, farenheit (sic) is first, and celsius is second, but in the program output, they are reversed. Why? Furthermore, the printf format string doesn't work (second printf call in the source). It won't print the values in the variables because the entire thing is a string literal. What on earth are you doing? Why do you have a screenshot of the first SICP lecture, one of the first exercises in K&R, and broken source code next to a working program that it obviously doesn't correspond to? I am bewildered and confused, lain.
Spooky · 2022-03-16 11:07
looking for information about multithreaded programming with c. commong design patterns would be useful. https://man7.org/linux/man-pages/man3/pthread_cleanup_pop.3p.html shows one good example also saw this around, which has some good resources https://randu.org/tutorials/threads/ has anyone found anything else useful?
Tyrell Wellick · 2022-03-18 12:06
>>30425 pthreads only if you must, otherwise fork
Yuki Nagato · 2022-03-18 22:27
>>30447 not a good suggestion at all
setq · 2022-03-18 22:45
>>30425 >looking for information about multithreaded programming with c. Use POSIX threads or OpenMP. * https://www.cs.cmu.edu/afs/cs/academic/class/15492-f07/www/pthreads.html (pthreads tutorial) * https://www.youtube.com/watch?v=_z-RS0rXg9s&list=PLzLzYGEbdY5lrUYSssHfk5ahwZERojgid&index=1 (a good tutorial series on Parallelism) >>30447 >fork Why not posix_spawn? >https://man7.org/linux/man-pages/man3/posix_spawn.3.html >>30449 Also, this.
limited · 2022-03-20 00:30
>>30451 jesus christ lainchan is 100% fuarrrking retarded. i can't believe these people think they deserve theri lives the post does not ask for a pthread tutorial here's a real resource: https://en.wikipedia.org/wiki/Concurrency_pattern
nibble · 2022-03-20 06:52
>>30449 Contrary, it's one of the best suggestions you can make. If you do not understand why, you never analyzed the subject deep enough yourself.
Trinity · 2022-03-20 06:55
>>30451 >Why not posix_spawn? 1st paragraph of description on that page answers your question.
Pulse · 2022-03-20 20:39
How did OP to get that cool UI?
McCarthy · 2022-03-20 20:56
>>30460 by overwatching anime style drawings , ofc !
HELIOS · 2022-03-21 16:13
could a C program identify the Raga within a song , then search for the same Raga within other contexts ? for example , identifying the Raga within a sample , then crawling the web for the same pattern in either visual , auditory , or other sensory data . my music theory severely lacks , however this concept appeals to me spiritually . I wonder whether creating new movements for the same Raga , would prove possible for a beginner such as myself . With a Raga , then hopefully I can find the feeling of a Naga .
Tyrell Wellick · 2022-03-21 18:16
For those who are interested in secure coding practices, check out: https://wiki.sei.cmu.edu/confluence/display/c/SEI+CERT+C+Coding+Standard Here is a good article about fork() vs. vfork(): https://gist.github.com/nicowilliams/a8a07b0fc75df05f684c23c18d7db234 There is also clone() (available in Linux) and rfork() (available in Plan9, FreeBSD and DragonFly BSD). IMO, posix_spawn() looks cleaner than fork() + exec(). Apparently someone created aspawn: https://github.com/NobodyXu/aspawn >aspawn - Asynchronous and more versatile replacement of posix_spawn() >POSIX threads There is also threads.h + stdatomic.h: https://en.cppreference.com/w/c/thread but almost everyone prefers POSIX threads. Check out ch. 12 of 21st Century C and APUE. >>30454 Concurrency vs Parallelism vs Multi-Processing can be a bit confusing. >the post does not ask for a pthread tutorial Read the post again (but the link you provided is good): >>30425 >looking for information about multithreaded programming with c >has anyone found anything else useful? <looking for information <anything else useful >>30460 To me it looks like customized FVWM: https://www.fvwm.org/Archive/Screenshots/ ... or perhaps WindowMaker? https://www.windowmaker.org/screenshots/
The Oracle · 2022-03-21 22:48
The Ten Commandments for C Programmers: https://www.lysator.liu.se/c/ten-commandments.html The free "Modern C" book: https://gustedt.gitlabpages.inria.fr/modern-c/ Agner's optimization manuals: https://agner.org/optimize/ Here is the #c @ Libera IRC channel's home page: https://www.iso-9899.info/wiki/Main_Page (it contains a lot of resources and links. you can also find links to drafts of the official C language standard aka ISO/IEC 9899. if you want to join/lurk the IRC channel (or perhaps use lainchan IRC channel) you should install Weechat or Irssi or Hexchat) Yet another POSIX threads tutorial with good pictures: http://www.csc.villanova.edu/~mdamian/threads/posixthreads.html Also, you might be interested in reading about green threads/fibers at some point: https://c9x.me/articles/gthreads/intro.html and https://graphitemaster.github.io/fibers/ https://github.com/geofft/vireo & http://libmill.org/ and/or http://libdill.org >>30477 There is also the A fork() in the road paper from M$ Research: https://www.microsoft.com/en-us/research/uploads/prod/2019/04/fork-hotos19.pdf I also found this lecture helpful: https://www.youtube.com/watch?v=uRYyj8tcDTE fork() can fail: https://rachelbythebay.com/w/2014/08/19/fork/ Also: vfork considered dangerous: https://ewontfix.com/7/ (from the author of musl)
Naomi Nascimento · 2022-03-24 04:43
>>30424 I had opened the wrong file for the screenshot >>30460 >>30477 I linked my gitlab-hosted dotfiles previously in this thread I wish to provide a bit of an update here. After so much that has happened in such a short amount of time, I took some time off from this project. It became somewhat upset with it anyway due to my inability to take my simple investment calculator and plot the output. I am now employed so my time to study is limited, but I do plan to do so snd retutn in the future. I think I will just skip the plotting attempt for now and retry at a later time. I am very thankful for all the kind comments and I am also greatful others have commented saying they have found use in this thread I made which originally was out of spite of a user saying I was a skid in my previous programming thread where I made vaersi, an interactive script to parse the 2021 VAERS CSV data. I still have to make a C equivilent just to learn how. My time as a poor NEET is now over and while I enjoy my newfound job I no longer can spend my days focusing on the growth of my mind (not that I honestly did that much anyway :). I hope to return though. I hope to better myself in more ways than one though. I am stuck normalfagging and pretending to be a well-adjusted member of society. See you all soon, lanions.
renames · 2022-03-25 09:58
>>30544 >Speaking for modern C (not K&R) - int main() / and x fun(void) for the compiler means actually the same as int main(void) / x fun(void) Bullshit. $ cat test.h int fun1(); int fun2(void); $ cat test.c #include "test.h" int main(void) { #if defined(FUN1) fun1(1, 2); #elif defined(FUN2) fun2(1, 2); #endif return 0; } $ gcc-10 -DFUN1 -Wall -Wextra -std=c11 -pedantic test.c -c -o test.o $ gcc-10 -DFUN2 -Wall -Wextra -std=c11 -pedantic test.c -c -o test.o test.c: In function ‘main’: test.c:8:2: error: too many arguments to function ‘fun2’ 8 | fun2(1, 2); | ^~~~ In file included from test.c:1: test.h:2:5: note: declared here 2 | int fun2(void); | ^~~~ C23 actually removes them, from what I understand. >The way to understand this is actually understand what () grouping means in C - they describe data thrown as a sequence on stack But that's wrong. () has different meaning according to the context (e.g. arithmetic grouping, casting & compound literals, etc...). And in your example, it does nothing, as the comma is the sequence operator that creates a sequence evaluating to the last value; the parens is just used as a priority operator.
Hiro Protagonist · 2022-03-27 16:19
Cobbled a Go-like (only it's bound to the scope, not the function) defer using gcc/clang extensions; can be done easily in C++ using destructors, of course: #include <stdio.h> #define PASTE(a, b) a ## b #if defined(__clang__) // Compile with CFLAGS=-fblocks LDLIBS=-lBlocksRuntime static inline void defer_cleanup (void (^*block) ()) {(*block)();} # define DEFER_VAR(a) PASTE(defer_var_, a) # define DEFER(BLOCK) __attribute__((cleanup(defer_cleanup))) \ __attribute__((unused)) void (^DEFER_VAR(__COUNTER__)) () = ^{BLOCK} #elif defined(__GNUC__) # define DEFER_VAR(a) PASTE(defer_var_, a) # define DEFER_FUN(a) PASTE(defer_fun_, a) # define DEFER_EXPAND(BLOCK, ID) void DEFER_FUN(ID) (__attribute__((unused)) int *a) {BLOCK}; \ __attribute__((cleanup(DEFER_FUN(ID)))) int DEFER_VAR(ID) # define DEFER(BLOCK) DEFER_EXPAND(BLOCK, __COUNTER__) #else # define DEFER(BLOCK) _Static_assert(false, "DEFER only works with GCC or Clang"); #endif int main(void) { DEFER(puts("hello");); FILE *stream = fopen("/dev/null", "r"); DEFER(fclose(stream);); }
Roger Pollack · 2022-04-01 17:19
So I had to dive in back into C because of a school assignment. I have to write some stuff working with sockets and the project will evolve week by week. I haven't done C in weeks and I never really understood pointers that well wo it has been a good amount of work. Hell, even just the string stuff has been kind of a hassle. I'm not going to lie tough, I've slowly been gaining a little more interest in C and am considering using it a little more or at least try to. The consooomer inside of me bought a copy of K&R because I always wanted to own one but I haven't actually read it. I might give it a read if this sudden interest is not gone by next week.
list · 2022-04-01 17:54
>>30602 A pointer points to a location, a memory address. You can Increment it to go to the next contiguous location, decrement it to go to the previous. To access the value stored at that location, you dereference your pointer. /*declare pointer myPtr*/ int* myPtr; /*declare integers myInt and myInt2*/ int myInt,myInt2; /*assign value "1" to myInt*/ myInt = 1; /*assign location of myInt to myPtr, note the use of "&" to get the location of myInt*/ myPtr = &myInt; /*assign to myInt2 the value stored at the where myPtr points to, note the use of "*" to dereference myPtr*/ myInt2 = *myPtr; /*since myPtr points to the location of myInt, myInt2 and myInt now have the same value*/ That's the very example i was given when it all "clicked". >flood detected fvck
Zhora · 2022-04-01 18:22
>>30604 Yes man thanks a lot. I tried to write a little program off the top of my head of what I remember about pointers: int n = 5; int *p = &n; printf("Some very basic pointer tests\n"); printf("n = %d\n", n); printf("Address p is pointing to = %d\n", &p); printf("Value of the address p is pointing to = %d\n", *p); This outputs what I was expecting it to output but the compiler throws me a warning: pointer.c:10:46: warning: format specifies type 'int' but the argument has type 'int **' [-Wformat] printf("Address p is pointing to= %d\n", &p); That's confusing.
Yamaoto Toshi · 2022-04-01 18:48
>>30605 This was a little harder to solve using Google than I was expecting. Turns out I have to use %p.
BloodCat · 2022-04-01 20:22
>>30605 The 3rd printf doesn't seem exactly right. &p is the address of p, but it seems you really wanted to print the value of p (which is the address of n).
Mario Rossi · 2022-04-01 21:02
>>30607 I guess it would have been better said as "Value of what p is pointing to"
Apoc · 2022-04-01 22:27
>>30606 I was going to post this, but it seems you figured it out yourself. Good! Come back and update us as you go!
Jens Hansen · 2022-04-06 13:12
I am currently (re)learning C using online resources as in where ever my search terms may lead me. It is an absolutely insane experience so far. It is a noble intention to teach and share knowledge, but the amount of mistakes in the code that is supposed to be an example is overwhelming to say the least. How do I even find out about it if I am not knowledgeable in the first place? Literally hours upon hours of checking code to debug what I could have done wrong until slowly an understanding emerges to prove that acually the teacher has made a mistake. I'm begging you, if you feel knowledgeable enough to actually teach other people and write about it online, please make sure even your most basic examples do what you actually claim them to do.
Linda Lee · 2022-04-06 13:53
>>30665 What resources are you using OP?
Backus · 2022-04-06 14:28
>>30666 It really depends on the search term. I use google and the term "FIFO queue C". I'm looking for an example of how to implement a first in, first out queue. The very first search result leads to https://data-flair.training/blogs/queue-in-c-cpp/ which seems to be a fully curated quality online course with the title "How Queues are Implemented with Arrays & Linked List". I followed the implementation example and it took me several hours to find out, that the example code is at one point mistakingly checking the queues TAIL pointer instead of the queues HEAD pointer. At least from what I can tell as somebody who is trying to understand and learn from those examples. This is an example of a website that offers what seem to be quality examples, worse results can be found in "personal blog post tutorials" and even worse examples of people confidently showing you how to do it on stackoverflow. I can even see certain questions emerge purely from the top search results giving erroneous examples. As another example I've seen hundreds of confused questions about how to properly send and receive data via sockets and they may very well be the result of some bad example code being within the top search result looking like some knowledgeable person is teaching you how to do it.
Frank Garza · 2022-04-06 16:16
>>30665 there is an existing thread >>29649
overriding · 2022-04-06 19:01
>>30667 implementing data structures in C like queues is a job or homework question. nobody's going to do an unpaid job for you, let alone do it properly. luckily other languages like C++ already have such data structures in their standard libraries
Backus · 2022-04-06 21:59
>>30665 At this stage, you should be less concerned about code quality and more about the big picture mathematics and logic. Once you get that stuff the little things will come naturally.