The C Programming Language

Brian W. Kernighan, Dennis M. Ritchie

Mentioned 127

Introduces the features of the C programming language, discusses data types, variables, operators, control flow, functions, pointers, arrays, and structures, and looks at the UNIX system interface

More on

Mentioned in questions and answers.

If you could go back in time and tell yourself to read a specific book at the beginning of your career as a developer, which book would it be?

I expect this list to be varied and to cover a wide range of things.

To search: Use the search box in the upper-right corner. To search the answers of the current question, use inquestion:this. For example:

inquestion:this "Code Complete"

Applying UML and Patterns by Craig Larman.

The title of the book is slightly misleading; it does deal with UML and patterns, but it covers so much more. The subtitle of the book tells you a bit more: An Introduction to Object-Oriented Analysis and Design and Iterative Development.

Masters of doom. As far as motivation and love for your profession go: it won't get any better than what's been described in this book, truthfully inspiring story!

Beginning C# 3.0: An Introduction to Object Oriented Programming

This is the book for those who want to understand the whys and hows of OOP using C# 3.0. You don't want to miss it.

alt text

Mastery: The Keys to Success and Long-Term Fulfillment, by George Leonard

It's about about what mindsets are required to reach mastery in any skill, and why. It's just awesome, and an easy read too.

Pro Spring is a superb introduction to the world of Inversion of Control and Dependency Injection. If you're not aware of these practices and their implications - the balance of topics and technical detail in Pro Spring is excellent. It builds a great case and consequent personal foundation.

Another book I'd suggest would be Robert Martin's Agile Software Development (ASD). Code smells, agile techniques, test driven dev, principles ... a well-written balance of many different programming facets.

More traditional classics would include the infamous GoF Design Patterns, Bertrand Meyer's Object Oriented Software Construction, Booch's Object Oriented Analysis and Design, Scott Meyer's "Effective C++'" series and a lesser known book I enjoyed by Gunderloy, Coder to Developer.

And while books are nice ... don't forget radio!

... let me add one more thing. If you haven't already discovered safari - take a look. It is more addictive than stack overflow :-) I've found that with my google type habits - I need the more expensive subscription so I can look at any book at any time - but I'd recommend the trial to anyone even remotely interested.

(ah yes, a little obj-C today, cocoa tomorrow, patterns? soa? what was that example in that cookbook? What did Steve say in the second edition? Should I buy this book? ... a subscription like this is great if you'd like some continuity and context to what you're googling ...)

Database System Concepts is one of the best books you can read on understanding good database design principles.

alt text

Algorithms in C++ was invaluable to me in learning Big O notation and the ins and outs of the various sort algorithms. This was published before Sedgewick decided he could make more money by dividing it into 5 different books.

C++ FAQs is an amazing book that really shows you what you should and shouldn't be doing in C++. The backward compatibility of C++ leaves a lot of landmines about and this book helps one carefully avoid them while at the same time being a good introduction into OO design and intent.

Here are two I haven't seen mentioned:
I wish I had read "Ruminations on C++" by Koenig and Moo much sooner. That was the book that made OO concepts really click for me.
And I recommend Michael Abrash's "Zen of Code Optimization" for anyone else planning on starting a programming career in the mid 90s.

Perfect Software: And Other Illusions about Testing


Perfect Software: And Other Illusions about Testing by Gerald M. Weinberg

ISBN-10: 0932633692

ISBN-13: 978-0932633699

Rapid Development by McConnell

The most influential programming book for me was Enough Rope to Shoot Yourself in the Foot by Allen Holub.

Cover of the book

O, well, how long ago it was.

I have a few good books that strongly influenced me that I've not seen on this list so far:

The Psychology of Everyday Things by Donald Norman. The general principles of design for other people. This may seem to be mostly good for UI but if you think about it, it has applications almost anywhere there is an interface that someone besides the original developer has to work with; e. g. an API and designing the interface in such a way that other developers form the correct mental model and get appropriate feedback from the API itself.

The Art of Software Testing by Glen Myers. A good, general introduction to testing software; good for programmers to read to help them think like a tester i. e. think of what may go wrong and prepare for it.

By the way, I realize the question was the "Single Most Influential Book" but the discussion seems to have changed to listing good books for developers to read so I hope I can be forgiven for listing two good books rather than just one.

alt text

C++ How to Program It is good for beginner.This is excellent book that full complete with 1500 pages.

Effective C++ and More Effective C++ by Scott Myers.

Inside the C++ object model by Stanley Lippman

I bough this when I was a complete newbie and took me from only knowing that Java existed to a reliable team member in a short time

Not a programming book, but still a very important book every programmer should read:

Orbiting the Giant Hairball by Gordon MacKenzie

The Pragmatic programmer was pretty good. However one that really made an impact when I was starting out was :

Windows 95 System Programming Secrets"

I know - it sounds and looks a bit cheesy on the outside and has probably dated a bit - but this was an awesome explanation of the internals of Win95 based on the Authors (Matt Pietrek) investigations using his own own tools - the code for which came with the book. Bear in mind this was before the whole open source thing and Microsoft was still pretty cagey about releasing documentation of internals - let alone source. There was some quote in there like "If you are working through some problem and hit some sticking point then you need to stop and really look deeply into that piece and really understand how it works". I've found this to be pretty good advice - particularly these days when you often have the source for a library and can go take a look. Its also inspired me to enjoy diving into the internals of how systems work, something that has proven invaluable over the course of my career.

Oh and I'd also throw in effective .net - great internals explanation of .Net from Don Box.

I recently read Dreaming in Code and found it to be an interesting read. Perhaps more so since the day I started reading it Chandler 1.0 was released. Reading about the growing pains and mistakes of a project team of talented people trying to "change the world" gives you a lot to learn from. Also Scott brings up a lot of programmer lore and wisdom in between that's just an entertaining read.

Beautiful Code had one or two things that made me think differently, particularly the chapter on top down operator precedence.


@Juan: I know Juan, I know - but there are some things that can only be learned by actually getting down to the task at hand. Speaking in abstract ideals all day simply makes you into an academic. It's in the application of the abstract that we truly grok the reason for their existence. :P

@Keith: Great mention of "The Inmates are Running the Asylum" by Alan Cooper - an eye opener for certain, any developer that has worked with me since I read that book has heard me mention the ideas it espouses. +1

I found the The Algorithm Design Manual to be a very beneficial read. I also highly recommend Programming Pearls.

This one isnt really a book for the beginning programmer, but if you're looking for SOA design books, then SOA in Practice: The Art of Distributed System Design is for you.

For me it was Design Patterns Explained it provided an 'Oh that's how it works' moment for me in regards to design patterns and has been very useful when teaching design patterns to others.

Code Craft by Pete Goodliffe is a good read!

Code Craft

The first book that made a real impact on me was Mastering Turbo Assembler by Tom Swan.

Other books that have had an impact was Just For Fun by Linus Torvalds and David Diamond and of course The Pragmatic Programmer by Andrew Hunt and David Thomas.

In addition to other people's suggestions, I'd recommend either acquiring a copy of SICP, or reading it online. It's one of the few books that I've read that I feel greatly increased my skill in designing software, particularly in creating good abstraction layers.

A book that is not directly related to programming, but is also a good read for programmers (IMO) is Concrete Mathematics. Most, if not all of the topics in it are useful for programmers to know about, and it does a better job of explaining things than any other math book I've read to date.

For me "Memory as a programming concept in C and C++" really opened my eyes to how memory management really works. If you're a C or C++ developer I consider it a must read. You will defiantly learn something or remember things you might have forgotten along the way.

Agile Software Development with Scrum by Ken Schwaber and Mike Beedle.

I used this book as the starting point to understanding Agile development.

Systemantics: How Systems Work and Especially How They Fail. Get it used cheap. But you might not get the humor until you've worked on a few failed projects.

The beauty of the book is the copyright year.

Probably the most profound takeaway "law" presented in the book:

The Fundamental Failure-Mode Theorem (F.F.T.): Complex systems usually operate in failure mode.

The idea being that there are failing parts in any given piece of software that are masked by failures in other parts or by validations in other parts. See a real-world example at the Therac-25 radiation machine, whose software flaws were masked by hardware failsafes. When the hardware failsafes were removed, the software race condition that had gone undetected all those years resulted in the machine killing 3 people.

It seems most people have already touched on the some very good books. One which really helped me out was Effective C#: 50 Ways to Improve your C#. I'd be remiss if I didn't mention The Tao of Pooh. Philosophy books can be good for the soul, and the code.

Discrete Mathematics For Computer Scientists

Discrete Mathematics For Computer Scientists by J.K. Truss.

While this doesn't teach you programming, it teaches you fundamental mathematics that every programmer should know. You may remember this stuff from university, but really, doing predicate logic will improve you programming skills, you need to learn Set Theory if you want to program using collections.

There really is a lot of interesting information in here that can get you thinking about problems in different ways. It's handy to have, just to pick up once in a while to learn something new.

I saw a review of Software Factories: Assembling Applications with Patterns, Models, Frameworks, and Tools on a blog talking also about XI-Factory, I read it and I must say this book is a must read. Altough not specifically targetted to programmers, it explains very clearly what is happening in the programming world right now with Model-Driven Architecture and so on..

Solid Code Optimizing the Software Development Life Cycle

Although the book is only 300 pages and favors Microsoft technologies it still offers some good language agnostic tidbits.

Managing Gigabytes is an instant classic for thinking about the heavy lifting of information.

My vote is "How to Think Like a Computer Scientist: Learning With Python" It's available both as a book and as a free e-book.

It really helped me to understand the basics of not just Python but programming in general. Although it uses Python to demonstrate concepts, they apply to most, if not all, programming languages. Also: IT'S FREE!

Object-Oriented Programming in Turbo C++. Not super popular, but it was the one that got me started, and was the first book that really helped me grok what an object was. Read this one waaaay back in high school. It sort of brings a tear to my eye...

My high school math teacher lent me a copy of Are Your Lights Figure Problem that I have re-read many times. It has been invaluable, as a developer, and in life generally.

I'm reading now Agile Software Development, Principles, Patterns and Practices. For those interested in XP and Object-Oriented Design, this is a classic reading.

alt text

Kernighan & Plauger's Elements of Programming Style. It illustrates the difference between gimmicky-clever and elegant-clever.

to get advanced in prolog i like these two books:

The Art of Prolog

The Craft of Prolog

really opens the mind for logic programming and recursion schemes.

Here's an excellent book that is not as widely applauded, but is full of deep insight: Agile Software Development: The Cooperative Game, by Alistair Cockburn.

What's so special about it? Well, clearly everyone has heard the term "Agile", and it seems most are believers these days. Whether you believe or not, though, there are some deep principles behind why the Agile movement exists. This book uncovers and articulates these principles in a precise, scientific way. Some of the principles are (btw, these are my words, not Alistair's):

  1. The hardest thing about team software development is getting everyone's brains to have the same understanding. We are building huge, elaborate, complex systems which are invisible in the tangible world. The better you are at getting more peoples' brains to share deeper understanding, the more effective your team will be at software development. This is the underlying reason that pair programming makes sense. Most people dismiss it (and I did too initially), but with this principle in mind I highly recommend that you give it another shot. You wind up with TWO people who deeply understand the subsystem you just built ... there aren't many other ways to get such a deep information transfer so quickly. It is like a Vulcan mind meld.
  2. You don't always need words to communicate deep understanding quickly. And a corollary: too many words, and you exceed the listener/reader's capacity, meaning the understanding transfer you're attempting does not happen. Consider that children learn how to speak language by being "immersed" and "absorbing". Not just language either ... he gives the example of some kids playing with trains on the floor. Along comes another kid who has never even SEEN a train before ... but by watching the other kids, he picks up the gist of the game and plays right along. This happens all the time between humans. This along with the corollary about too many words helps you see how misguided it was in the old "waterfall" days to try to write 700 page detailed requirements specifications.

There is so much more in there too. I'll shut up now, but I HIGHLY recommend this book!

alt text

The Back of the Napkin, by Dan Roam.

The Back of the Napkin

A great book about visual thinking techniques. There is also an expanded edition now. I can't speak to that version, as I do not own it; yet.

Agile Software Development by Alistair Cockburn

Do users ever touch your code? If you're not doing solely back-end work, I recommend About Face: The Essentials of User Interface Design — now in its third edition (linked). I used to think my users were stupid because they didn't "get" my interfaces. I was, of course, wrong. About Face turned me around.

"Writing Solid Code: Microsoft's Techniques for Developing Bug-Free C Programs (Microsoft Programming Series)" by Steve MacGuire.

Interesting what a large proportion the books mentioned here are C/C++ books.

While not strictly a software development book, I would highly recommend that Don't Make me Think! be considered in this list.

As so many people have listed Head First Design Patterns, which I agree is a very good book, I would like to see if so many people aware of a title called Design Patterns Explained: A New Perspective on Object-Oriented Design.

This title deals with design patterns excellently. The first half of the book is very accessible and the remaining chapters require only a firm grasp of the content already covered The reason I feel the second half of the book is less accessible is that it covers patterns that I, as a young developer admittedly lacking in experience, have not used much.

This title also introduces the concept behind design patterns, covering Christopher Alexander's initial work in architecture to the GoF first implementing documenting patterns in SmallTalk.

I think that anyone who enjoyed Head First Design Patterns but still finds the GoF very dry, should look into Design Patterns Explained as a much more readable (although not quite as comprehensive) alternative.

Even though i've never programmed a game this book helped me understand a lot of things in a fun way.

How influential a book is often depends on the reader and where they were in their career when they read the book. I have to give a shout-out to Head First Design Patterns. Great book and the very creative way it's written should be used as an example for other tech book writers. I.e. it's written in order to facilitate learning and internalizing the concepts.

Head First Design Patterns

97 Things Every Programmer Should Know

alt text

This book pools together the collective experiences of some of the world's best programmers. It is a must read.

Extreme Programming Explained: Embrace Change by Kent Beck. While I don't advocate a hardcore XP-or-the-highway take on software development, I wish I had been introduced to the principles in this book much earlier in my career. Unit testing, refactoring, simplicity, continuous integration, cost/time/quality/scope - these changed the way I looked at development. Before Agile, it was all about the debugger and fear of change requests. After Agile, those demons did not loom as large.

One of my personal favorites is Hacker's Delight, because it was as much fun to read as it was educational.

I hope the second edition will be released soon!

You.Next(): Move Your Software Development Career to the Leadership Track ~ Michael C. Finley (Author), Honza Fedák (Author) link text

I've been arounda while, so most books that I have found influential don't necessarily apply today. I do believe it is universally important to understand the platform that you are developing for (both hardware and OS). I also think it's important to learn from other peoples mistakes. So two books I would recommend are:

Computing Calamities and In Search of Stupidity: Over Twenty Years of High Tech Marketing Disasters

Working Effectively with Legacy Code is a really amazing book that goes into great detail about how to properly unit test your code and what the true benefit of it is. It really opened my eyes.

As Joel points out in Stack Overflow podcast #34, in C Programming Language (aka: K & R), there is mention of this property of arrays in C: a[5] == 5[a]

Joel says that it's because of pointer arithmetic but I still don't understand. Why does a[5] == 5[a]?

The C standard defines the [] operator as follows:

a[b] == *(a + b)

Therefore a[5] will evaluate to:

*(a + 5)

and 5[a] will evaluate to:

*(5 + a)

a is a pointer to the first element of the array. a[5] is the value that's 5 elements further from a, which is the same as *(a + 5), and from elementary school math we know those are equal (addition is commutative).

To follow the example of The Definitive C++ Book Guide and List for C Books here is a wiki post for organization.

A tag search for "C" and "Books" returns no complete book list results as of writing this question. That search is here.

This post is to providing QUALITY books and an approximate skill level. Maybe we can add a short blurb/description about each book that you have personally read / benefited from. Feel free to debate quality, headings, etc.

Reference Style - All Levels



Above Intermediate

Uncategorized Additional C Programming Books

C Unleashed : is also a good book. Its not ideal or anything. But for intermediate programmers, its definitely worth practising programs written in this book.

I added The Standard C Library by P.J. Plauger. It contains complete source code to an implementation of the C89 standard library along with extensive discussion. It was very influential to my C programming style. As a library it is much more accessible than, say, STL.

Problem Solving and Program Design in C (6th Edition) is an intermediate level book. If you have other C Advanced books then this is not an ideal book to buy but its definitely worth going through once.

I think the knowledge you're looking for is to be found not in books about C but in books and articles about system design. These are fairly thin on the ground, unfortunately. You might consider

  • Abstraction and Specification in Program Development by Barbara Liskov and John Guttag (not the newer Java-based version by Liskov alone). It is an undergraduate text but has some ideas worth thinking about.

  • Books from the late 1970s and early 1980s by Yourdon and Myers on structured design (one is called Composite/Structured Design.

  • For an example of how to organize a big C project as a bunch of useful libraries, you can't beat C Interfaces and Implementations by Dave Hanson. Basically Hanson took all the code he'd written as part of building Icon and lcc and pulled out the best bits in a form that other people could reuse for their own projects. It's a model of good C programming using modern design techniques (including Liskov's data abstraction).

Beginner: Applications Programming in ANSI C, by Johnsonbaugh & Kalin

Intermediate: Data Structures - An Advanced Approach Using C, by Esakov and Weiss



  • Algorithms in C by Robert Sedgewick: gives you a real grasp of implementing algorithms in C; very lucid and clear; you will probably throw away all your algorithms books and keep this one


I'd like to make an anti-recommendation. Under no circumstances should you read any books by Herbert Schildt. In particular, you should stay away from C: The Complete Reference.

Having read the same books, hopefully I can help with a few more:

And finally a good cookbook-like one from comp.lang.c contributors:

It wasn't that long ago that I was a beginning coder, trying to find good books/tutorials on languages I wanted to learn. Even still, there are times I need to pick up a language relatively quickly for a new project I am working on. The point of this post is to document some of the best tutorials and books for these languages. I will start the list with the best I can find, but hope you guys out there can help with better suggestions/new languages. Here is what I found:

Since this is now wiki editable, I am giving control up to the community. If you have a suggestion, please put it in this section. I decided to also add a section for general be a better programmer books and online references as well. Once again, all recommendations are welcome.

General Programming

Online Tutorials
Foundations of Programming By Karl Seguin - From Codebetter, its C# based but the ideas ring true across the board, can't believe no-one's posted this yet actually.
How to Write Unmaintainable Code - An anti manual that teaches you how to write code in the most unmaintable way possible. It would be funny if a lot of these suggestions didn't ring so true.
The Programming Section of Wiki Books - suggested by Jim Robert as having a large amount of books/tutorials on multiple languages in various stages of completion
Just the Basics To get a feel for a language.

Code Complete - This book goes without saying, it is truely brilliant in too many ways to mention.
The Pragmatic Programmer - The next best thing to working with a master coder, teaching you everything they know.
Mastering Regular Expressions - Regular Expressions are an essential tool in every programmer's toolbox. This book, recommended by Patrick Lozzi is a great way to learn what they are capable of.
Algorithms in C, C++, and Java - A great way to learn all the classic algorithms if you find Knuth's books a bit too in depth.


Online Tutorials
This tutorial seems to pretty consise and thourough, looked over the material and seems to be pretty good. Not sure how friendly it would be to new programmers though.
K&R C - a classic for sure. It might be argued that all programmers should read it.
C Primer Plus - Suggested by Imran as being the ultimate C book for beginning programmers.
C: A Reference Manual - A great reference recommended by Patrick Lozzi.


Online Tutorials
The tutorial on seems to be the most complete. I found another tutorial here but it doesn't include topics like polymorphism, which I believe is essential. If you are coming from C, this tutorial might be the best for you.

Another useful tutorial, C++ Annotation. In Ubuntu family you can get the ebook on multiple format(pdf, txt, Postscript, and LaTex) by installing c++-annotation package from Synaptic(installed package can be found in /usr/share/doc/c++-annotation/.

The C++ Programming Language - crucial for any C++ programmer.
C++ Primer Plus - Orginally added as a typo, but the amazon reviews are so good, I am going to keep it here until someone says it is a dud.
Effective C++ - Ways to improve your C++ programs.
More Effective C++ - Continuation of Effective C++.
Effective STL - Ways to improve your use of the STL.
Thinking in C++ - Great book, both volumes. Written by Bruce Eckel and Chuck Ellison.
Programming: Principles and Practice Using C++ - Stroustrup's introduction to C++.
Accelerated C++ - Andy Koenig and Barbara Moo - An excellent introduction to C++ that doesn't treat C++ as "C with extra bits bolted on", in fact you dive straight in and start using STL early on.


FORTH, a text and reference. Mahlon G. Kelly and Nicholas Spies. ISBN 0-13-326349-5 / ISBN 0-13-326331-2. 1986 Prentice-Hall. Leo Brodie's books are good but this book is even better. For instance it covers defining words and the interpreter in depth.


Online Tutorials
Sun's Java Tutorials - An official tutorial that seems thourough, but I am not a java expert. You guys know of any better ones?
Head First Java - Recommended as a great introductory text by Patrick Lozzi.
Effective Java - Recommended by pek as a great intermediate text.
Core Java Volume 1 and Core Java Volume 2 - Suggested by FreeMemory as some of the best java references available.
Java Concurrency in Practice - Recommended by MDC as great resource for concurrent programming in Java.

The Java Programing Language


Online Tutorials - The online documentation for this language is pretty good. If you know of any better let me know.
Dive Into Python - Suggested by Nickola. Seems to be a python book online.


Online Tutorials
perldoc perl - This is how I personally got started with the language, and I don't think you will be able to beat it.
Learning Perl - a great way to introduce yourself to the language.
Programming Perl - greatly referred to as the Perl Bible. Essential reference for any serious perl programmer.
Perl Cookbook - A great book that has solutions to many common problems.
Modern Perl Programming - newly released, contains the latest wisdom on modern techniques and tools, including Moose and DBIx::Class.


Online Tutorials
Adam Mika suggested Why's (Poignant) Guide to Ruby but after taking a look at it, I don't know if it is for everyone. Found this site which seems to offer several tutorials for Ruby on Rails.
Programming Ruby - suggested as a great reference for all things ruby.

Visual Basic

Online Tutorials
Found this site which seems to devote itself to visual basic tutorials. Not sure how good they are though.


Online Tutorials
The main PHP site - A simple tutorial that allows user comments for each page, which I really like. PHPFreaks Tutorials - Various tutorials of different difficulty lengths.
Quakenet/PHP tutorials - PHP tutorial that will guide you from ground up.


Online Tutorials
Found a decent tutorial here geared toward non-programmers. Found another more advanced one here. Nickolay suggested A reintroduction to javascript as a good read here.

Head first JavaScript
JavaScript: The Good Parts (with a Google Tech Talk video by the author)


Online Tutorials
C# Station Tutorial - Seems to be a decent tutorial that I dug up, but I am not a C# guy.
C# Language Specification - Suggested by tamberg. Not really a tutorial, but a great reference on all the elements of C#
C# to the point - suggested by tamberg as a short text that explains the language in amazing depth


nlucaroni suggested the following:
OCaml for Scientists Introduction to ocaml
Using Understand and unraveling ocaml: practice to theory and vice versa
Developing Applications using Ocaml - O'Reilly
The Objective Caml System - Official Manua


Online Tutorials
nlucaroni suggested the following:
Explore functional programming with Haskell
Real World Haskell
Total Functional Programming


wfarr suggested the following:
The Little Schemer - Introduction to Scheme and functional programming in general
The Seasoned Schemer - Followup to Little Schemer.
Structure and Interpretation of Computer Programs - The definitive book on Lisp (also available online).
Practical Common Lisp - A good introduction to Lisp with several examples of practical use.
On Lisp - Advanced Topics in Lisp
How to Design Programs - An Introduction to Computing and Programming
Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp - an approach to high quality Lisp programming

What about you guys? Am I totally off on some of there? Did I leave out your favorite language? I will take the best comments and modify the question with the suggestions.

Java: SCJP for Java 6. I still use it as a reference.


O'Reilly Book:

  1. Real World Haskell, a great tutorial-oriented book on Haskell, available online and in print.

My favorite general, less academic online tutorials:

  1. The Haskell wikibook which contains all of the excellent Yet Another Haskell Tutorial. (This tutorial helps with specifics of setting up a Haskell distro and running example programs, for example.)
  2. Learn you a Haskell for Great Good, in the spirit of Why's Poignant Guide to Ruby but more to the point.
  3. Write yourself a Scheme in 48 hours. Get your hands dirty learning Haskell with a real project.

Books on Functional Programming with Haskell:

  1. Lambda calculus, combinators, more theoretical, but in a very down to earth manner: Davie's Introduction to Functional Programming Systems Using Haskell
  2. Laziness and program correctness, thinking functionally: Bird's Introduction to Functional Programming Using Haskell

Some books on Java I'd recommend:

For Beginners: Head First Java is an excellent introduction to the language. And I must also mention Head First Design Patterns which is a great resource for learners to grasp what can be quite challenging concepts. The easy-going fun style of these books are ideal for ppl new to programming.

A really thorough, comprehensive book on Java SE is Bruce Eckel's Thinking In Java v4. (At just under 1500 pages it's good for weight-training as well!) For those of us not on fat bank-bonuses there are older versions available for free download.

Of course, as many ppl have already mentioned, Josh Bloch's Effective Java v2 is an essential part of any Java developer's library.

Let's not forget Head First Java, which could be considered the essential first step in this language or maybe the step after the online tutorials by Sun. It's great for the purpose of grasping the language concisely, while adding a bit of fun, serving as a stepping stone for the more in-depth books already mentioned.

Sedgewick offers great series on Algorithms which are a must-have if you find Knuth's books to be too in-depth. Knuth aside, Sedgewick brings a solid approach to the field and he offers his books in C, C++ and Java. The C++ books could be used backwardly on C since he doesn't make a very large distinction between the two languages in his presentation.

Whenever I'm working on C, C:A Reference Manual, by Harbison and Steele, goes with me everywhere. It's concise and efficient while being extremely thorough making it priceless(to me anyways).

Languages aside, and if this thread is to become a go-to for references in which I think it's heading that way due to the number of solid contributions, please include Mastering Regular Expressions, for reasons I think most of us are aware of... some would also say that regex can be considered a language in its own right. Further, its usefulness in a wide array of languages makes it invaluable.

C: “Programming in C”, Stephen G. Kochan, Developer's Library.

Organized, clear, elaborate, beautiful.


The first one is good for beginners and the second one requires more advanced level in C++.

I know this is a cross post from here... but, I think one of the best Java books is Java Concurrency in Practice by Brian Goetz. A rather advanced book - but, it will wear well on your concurrent code and Java development in general.


C# to the Point by Hanspeter Mössenböck. On a mere 200 pages he explains C# in astonishing depth, focusing on underlying concepts and concise examples rather than hand waving and Visual Studio screenshots.

For additional information on specific language features, check the C# language specification ECMA-334.

Framework Design Guidelines, a book by Krzysztof Cwalina and Brad Abrams from Microsoft, provides further insight into the main design decisions behind the .NET library.

For Lisp and Scheme (hell, functional programming in general), there are few things that provide a more solid foundation than The Little Schemer and The Seasoned Schemer. Both provide a very simple and intuitive introduction to both Scheme and functional programming that proves far simpler for new students or hobbyists than any of the typical volumes that rub off like a nonfiction rendition of War & Peace.

Once they've moved beyond the Schemer series, SICP and On Lisp are both fantastic choices.

For C++ I am a big fan of C++ Common Knowledge: Essential Intermediate Programming, I like that it is organized into small sections (usually less than 5 pages per topic) So it is easy for me to grab it and read up on concepts that I need to review.

It is a must read for me the night before and on the plane to a job interview.

C Primer Plus, 5th Edition - The C book to get if you're learning C without any prior programming experience. It's a personal favorite of mine as I learned to program from this book. It has all the qualities a beginner friendly book should have:

  • Doesn't assume any prior exposure to programming
  • Enjoyable to read (without becoming annoying like For Dummies /
  • Doesn't oversimplify

For Javascript:

For PHP:

For OO design & programming, patterns:

For Refactoring:


  • C - The C Programming Language - Obviously I had to reference K&R, one of the best programming books out there full stop.
  • C++ - Accelerated C++ - This clear, well written introduction to C++ goes straight to using the STL and gives nice, clear, practical examples. Lives up to its name.
  • C# - Pro C# 2008 and the .NET 3.5 Platform - Bit of a mouthful but wonderfully written and huge depth.
  • F# - Expert F# - Designed to take experienced programmers from zero to expert in F#. Very well written, one of the author's invented F# so you can't go far wrong!
  • Scheme - The Little Schemer - Really unique approach to teaching a programming language done really well.
  • Ruby - Programming Ruby - Affectionately known as the 'pick axe' book, this is THE defacto introduction to Ruby. Very well written, clear and detailed.

I know this is a really basic question, but I've just started with some basic C++ programming after coding a few projects with high-level languages.

Basically I have three questions:

  1. Why use pointers over normal variables?
  2. When and where should I use pointers?
  3. How do you use pointers with arrays?

Pointers are one way of getting an indirect reference to another variable. Instead of holding the value of a variable, they tell you its address. This is particularly useful when dealing with arrays, since using a pointer to the first element in an array (its address) you can quickly find the next element by incrementing the pointer (to the next address location).

The best explanation of pointers and pointer arithmetic that I've read is in K & R's The C Programming Language. A good book for beginning learning C++ is C++ Primer.

I want to know how malloc and free work.

int main()

    unsigned char *p = (unsigned char*)malloc(4*sizeof(unsigned char));
    strcpy((char*)p,"abcdabcd"); // **deliberately storing 8bytes**
    cout << p;
    free(p); // Obvious Crash, but I need how it works and why crash.
    cout << p;
    return 0;

I would be really grateful if the answer is in depth at memory level, if it's possible.

There's a sample implementation of malloc() and free() in The Book (Kernighan and Ritchie "The C Programming Language"). Since you had to ask, you haven't read it - go forth and read it, and repent of your sinful ways. :D

Today I reached page 167 of The C Programming Language (second edition Brian W. Kernighan & Dennis M. Ritchie) and found that the author says I must cast malloc. Here is the part from the book:

7.8.5 Storage Management

The functions malloc and calloc obtain blocks of memory dynamically.

void *malloc(size_t n)

returns a pointer to n bytes of uninitialized storage, or NULL if the request cannot be satisfied.

void *calloc(size_t n, size_t size)

returns a pointer to enough free space for an array of n objects of the specified size, or NULL if the request cannot be satisfied. The storage is initialized to zero. The pointer returned by malloc or calloc has the proper alignment for the object in question, but it must be cast into the appropriate type, as in

int *ip;
ip = (int *) calloc(n, sizeof(int));

I already know that malloc (and its family) returns type void*, and there are good explanations why not to cast malloc.

But my question is: Why does the book say I should cast it?


In pre-ANSI C -- as described in K&R-1 -- malloc() returned a char * and it was necessary to cast its return value in all cases where the receiving variable was not also a char *. The new void * type in Standard C makes these contortions unnecessary.

To save anybody from the embarrassment of leaping needlessly to the defence of K&R-2, I asked Dennis Ritchie for an opinion that I could quote on the validity of the sentence cited above from page 142. He replied:

In any case, now that I reread the stuff on p. 142, I think it's wrong; it's written in such a way that it's not just defensive against earlier rules, it misrepresents the ANSI rules.

Being an aspiring Apple developer, I want to get the opinions of the community if it is better to learn C first before moving into Objective-C and ultimately the Cocoa Framework?

My gut says learn C, which will give me a good foundation.

You can readily enough learn C and Objective-C at the same time -- there's certainly no need to learn the minutiae of C (including pointer arithmetic and so on) before starting with Objective-C's additions to the language, and as a novice programmer getting underway with Objective-C quickly may help you to start "thinking in objects" more quickly.

In terms of available resources, Apple's documentation does typically assume familiarity with C, so starting with The Objective-C 2.0 Programming Language won't be of much benefit to you. I would invest in a copy of Programming in Objective-C by Stephen Kochan (depending on how quickly you want to get underway, you may consider waiting for the second edition):

Programming Objective-C Developers Library Programming Objective-C 2.0 Developers Library

It assumes no prior experience, and teaches you Objective-C and as much C as you need.

If you're feeling a little ambitious, you might start with Scott Stevenson's "Learn C" Tutorial, but it does have some prerequisites ("You should already know at least one scripting or programming language, including functions, variables and loops. You'll also need to type commands into the Mac OS X Terminal.").

(Just for the record and for context: I learned both at the same time back in 1991 -- it didn't seem to do me any harm. I did, though, have a background in BASIC, Pascal, Logo, and LISP.)

Do you want to be a hard-core developer? Then learn c first.

The books you need to completely master c are some of the best writings in technology. Here's what you need:

C Programming Language

The Standard C Library

Although people seem to like to complain about C++, I haven't been able to find much evidence as to why you would want to choose C over C++. C doesn't seem to get nearly as much flak and if C++ has all these problems why can't you just restrict yourself to the C subset? What are your thoughts/experience?

I take the other view: why use C++ instead of C?

The book The C Programming Language (aka: K&R) tells you clearly how to do everything the language can do in under 300 pages. It's a masterpiece of minimalism. No C++ book even comes close.

The obvious counterargument is that the same could be said of most, if not all, modern languages -- they also can't tell you how to do everything in only a few hundred pages. True. So why use C++ instead? Feature richness? Power? If you need something more feature rich or powerful then go with C#, Objective C, Java, or something else like that. Why burden yourself with the complexities of C++? If you need the degree of control C++ grants then I argue to use C. C can do anything and can do it well.

In C, are the shift operators (<<, >>) arithmetic or logical?

According to K&R 2nd edition the results are implementation-dependent for right shifts of signed values.

Wikipedia says that C/C++ 'usually' implements an arithmetic shift on signed values.

Basically you need to either test your compiler or not rely on it. My VS2008 help for the current MS C++ compiler says that their compiler does an arithmetic shift.

Are there any good books for a relatively new but not totally new *nix user to get a bit more in depth knowledge (so no "Linux for dummies")? For the most part, I'm not looking for something to read through from start to finish. Rather, I'd rather have something that I can pick up and read in chunks when I need to know how to do something or whenever I have one of those "how do I do that again?" moments. Some areas that I'd like to see are:

  • command line administration
  • bash scripting
  • programming (although I'd like something that isn't just relevant for C programmers)

I'd like this to be as platform-independent as possible (meaning it has info that's relevant for any linux distro as well as BSD, Solaris, OS X, etc), but the unix systems that I use the most are OS X and Debian/Ubuntu. So if I would benefit the most from having a more platform-dependent book, those are the platforms to target.

If I can get all this in one book, great, but I'd rather have a bit more in-depth material than coverage of everything. So if there are any books that cover just one of these areas, post it. Hell, post it even if it's not relevant to any of those areas and you think it's something that a person in my position should know about.

I've wiki'd this post - could those with sufficient rep add in items to it.

System administration, general usage books


Specific tools (e.g. Sendmail)

Various of the books from O'Reilly and other publishers cover specific topics. Some of the key ones are:

Some of these books have been in print for quite a while and are still relevant. Consequently they are also often available secondhand at much less than list price. Amazon marketplace is a good place to look for such items. It's quite a good way to do a shotgun approach to topics like this for not much money.

As an example, in New Zealand technical books are usurously expensive due to a weak kiwi peso (as the $NZ is affectionately known in expat circles) and a tortuously long supply chain. You could spend 20% of a week's after-tax pay for a starting graduate on a single book. When I was living there just out of university I used this type of market a lot, often buying books for 1/4 of their list price - including the cost of shipping to New Zealand. If you're not living in a location with tier-1 incomes I recommend this.

E-Books and on-line resources (thanks to israkir for reminding me):

  • The Linux Documentation project (, has many specific topic guides known as HowTos that also often concern third party OSS tools and will be relevant to other Unix variants. It also has a series of FAQ's and guides.

  • Unix Guru's Universe is a collection of unix resources with a somewhat more old-school flavour.

  • Google. There are many, many unix and linux resources on the web. Search strings like unix commands or learn unix will turn up any amount of online resources.

  • Safari. This is a subscription service, but you can search the texts of quite a large number of books. I can recommend this as I've used it. They also do site licences for corporate customers.

Some of the philosophy of Unix:

I recommend the Armadillo book from O'Reilly for command line administration and shell scripting.

alt text


Unix Programming Environment by Kernighan and Pike will give you solid foundations on all things Unix and should cover most of your questions regarding shell command line scripting etc.

The Armadillo book by O'Reilly will add the administration angle. It has served me well!

Good luck!

The aforementioned Unix Power Tools is a must. Other classics are sed&awk and Mastering Regular Expressions. I also like some books from the O'Reilly "Cookbook" series:

One of the things which I miss while writing programs in C is a dictionary data structure. What's the most convenient way to implement one in C? I am not looking for performance, but ease of coding it from scratch. I don't want it to be generic either -- something like string->int will do. But I do want it to be able to store an arbitrary number of items.

This is intended more as an exercise. I know that there are 3rd party libraries available which one can use. But consider for a moment, that they don't exist. In such a situation what's the quickest way you can implement a dictionary satisfying the above requirements.

Section 6.6 of The C Programming Language presents a simple dictionary (hashtable) data structure. I don't think a useful dictionary implementation could get any simpler than this. For your convenience, I reproduce the code here.

struct nlist { /* table entry: */
    struct nlist *next; /* next entry in chain */
    char *name; /* defined name */
    char *defn; /* replacement text */

#define HASHSIZE 101
static struct nlist *hashtab[HASHSIZE]; /* pointer table */

/* hash: form hash value for string s */
unsigned hash(char *s)
    unsigned hashval;
    for (hashval = 0; *s != '\0'; s++)
      hashval = *s + 31 * hashval;
    return hashval % HASHSIZE;

/* lookup: look for s in hashtab */
struct nlist *lookup(char *s)
    struct nlist *np;
    for (np = hashtab[hash(s)]; np != NULL; np = np->next)
        if (strcmp(s, np->name) == 0)
          return np; /* found */
    return NULL; /* not found */

char *strdup(char *);
/* install: put (name, defn) in hashtab */
struct nlist *install(char *name, char *defn)
    struct nlist *np;
    unsigned hashval;
    if ((np = lookup(name)) == NULL) { /* not found */
        np = (struct nlist *) malloc(sizeof(*np));
        if (np == NULL || (np->name = strdup(name)) == NULL)
          return NULL;
        hashval = hash(name);
        np->next = hashtab[hashval];
        hashtab[hashval] = np;
    } else /* already there */
        free((void *) np->defn); /*free previous defn */
    if ((np->defn = strdup(defn)) == NULL)
       return NULL;
    return np;

char *strdup(char *s) /* make a duplicate of s */
    char *p;
    p = (char *) malloc(strlen(s)+1); /* +1 for ’\0’ */
    if (p != NULL)
       strcpy(p, s);
    return p;

Note that if the hashes of two strings collide, it may lead to an O(n) lookup time. You can reduce the likelihood of collisions by increasing the value of HASHSIZE. For a complete discussion of the data structure, please consult the book.

I have started programming practice on codechef and have been confused by the difference between C and C99. What does C mean here? Is it C89? Check the languages at the bottom of this submit. It contains both C and C99.

I found on the internet something called GNU C. Is there a different C for linux/unix systems? Are these compliant to the C standards by ANSI? I have also read in some places "C99 strict". What is this?

Are there any other different standards of C in use? Is there something called C 4.3.2 or is it the gcc version in current use?


This, This, This helped. I'll search more and edit the things that are left unanswered.

I am not a programming newbie. I know what C language is. I know that there are the different C standards by ANSI like C89, C99 and C11.

  • Everything before standardization is generally called "K&R C", after the famous book, with Dennis Ritchie, the inventor of the C language, as one of the authors. This was "the C language" from 1972-1989.

  • The first C standard was released 1989 nationally in USA, by their national standard institute ANSI. This release is called C89 or ANSI-C. From 1989-1990 this was "the C language".

  • The year after, the American standard was accepted internationally and published by ISO (ISO 9899:1990). This release is called C90. Technically, it is the same standard as C89/ANSI-C. Formally, it replaced C89/ANSI-C, making them obsolete. From 1990-1999, C90 was "the C language".

    Please note that since 1989, ANSI haven't had anything to do with the C language. Programmers still speaking about "ANSI C" generally haven't got a clue about what it means. ISO "owns" the C language, through the standard ISO 9899.

  • In 1999, the C standard was revised, lots of things changed (ISO 9899:1999). This version of the standard is called C99. From 1999-2011, this was "the C language". Most C compilers still follow this version.

  • In 2011, the C standard was again changed (ISO 9899:2011). This version is called C11. It is currently the definition of "the C language".

"C99 strict" likely refers to a compiler setting forcing a compiler to follow the standard by the letter. There is a term conforming implementation in the C standard. Essentially it means: "this compiler actually implements the C language correctly". Programs that implement the C language correctly are formally called strictly conforming programs.

"GNU C" can mean two things. Either the C compiler itself that comes as part of the GNU Compiler Collection (GCC). Or it can mean the non-standard default setup that the GCC C compiler uses. If you compile with gcc program.c then you don't compile according to the C standard, but rather a non-standard GNU setup, which may be referred to as "GNU C". For example, the whole Linux kernel is made in non-standard GNU C, and not in standard C.

If you want to compile your programs according to the C standard, you should type gcc -std=c99 -pedantic-errors. Replace c99 with c11 if your GCC version supports it.

This question may be naive, but:

  • is there const keyword in C?
  • since which version?
  • are there any semantic and/or syntactic differences between const in C and C++?

Yes, const has been there since at least since ANSI C (aka C89).

It certainly appears in my copy of "The C Programming Language (2nd Edition)", Kernighan & Ritchie (published in 1988).

Relevant extract:

The const and volatile properties are new with the ANSI standard. The purpose of const is to announce objects that may be placed in read-only memory, and perhaps to increase opportunities for optimization.

I absolutely loved Dive Into Python when I picked up Python.

In fact, "tutorials" such as Dive Into Python work really well for me; short brief syntax explanations, and plenty of examples to get things going.

I learn really well via examples.

I have programming experience in Java, Scheme, Python, PHP, Javascript, etc.

Is there anywhere you would recommend online to quickly pick up the C programming language, and best practices?

When I learned C in the late 1980's I preferred Kochan's Programming in C (to K&R and a couple other lesser books). I see it's up to a third edition now, and there is a more recent version for Objective C.

I consider myself an experienced Java developer and am planning to get started with learning C++.

If you had same experience, i.e learn C++ after Java, I would like to hear your thoughts on what is the best approach at doing this.

[Update] "the best approach" was not well quantified. What I am looking for is to leverage my existing java knowledge and programming experience so that I can quickly ramp up on C++.

K&R and Stroustrup are classics, and eventually you should get them, but I don't think they are good introduction for C++ beginners. Thinking in modern C++ is thinking in classes, templates, exceptions, and streams, none of which available in C language.

I would recommend a college-level textbook on C++ like Deitel and Deitel. alt text

After playing around, you should focus on learning to write a class that behaves like a built-in class. That means providing a copy constructor, operator=, operator==, operator<<, etc.. Along the way you'll meet various concepts embedded in the language of C++. I would agree with others on Effective C++ is a must read once you are comfortable with the basics.

Others have already specified the required books. I would like to add just couple of points to be noted: ( as background is java)

  • C++ doesnot provide you the Garbage collection ( as in Java). Hence, you must be very perticular about memory leaks. Always use delete the memory allocated on heap using new. Try to remember the Free-Store management in FAQ while writing the C++ applications.
  • Most often in C++ you may have to work with pointers ( missing in Java). Learn pointers ( books suggested by @Charlie Martin) effectively and use them.
  • One you are familiar with C++, learn the basics of STL and use effectively. ( Book By Josuttis and Scott Meyers)

Good luck.

I've taught C++ to Java people, even though I learned them the other direction.

Are you comfortable with C? If not, read Kernighan and Ritchie. Many many peculiarities of C++ are explained by the desire for C++ to be a "Better C" with C's basic expression syntax.

You should get Stroustrup.

I think well of Thinking in C++ by Bruce Eckels.

I've used The C++ FAQ Book, by Cline, Lomow, and Girou; I refer to it pretty often. Marshall Cline has C++ FAQ content on his site, too.


You might also look at C++ for Java Programmers. I don't know the book but it looks decent.

Here is a program I'm trying to run straight from section 1.9 of "The C Programming Language".

#include <stdio.h>
#define MAXLINE 1000

int getline(char line[], int maxline);
void copy(char to[], char from[]);

    int len;
    int max;
    char line[MAXLINE];
    char longest[MAXLINE];

    max = 0;
    while ((len = getline(line, MAXLINE)) > 0)
        if (len > max) {
        max = len;
        copy(longest, line);
    if (max > 0)
        printf("%s", longest);
return 0;

int getline(char s[], int lim)
    int c, i;

    for (i=0; i<lim-1 && (c=getchar()) !=EOF && c != '\n'; ++i)
        s[i] = c;
    if (c == '\n') {
        s[i] = c;
    s[i] = '\0';
    return i;

void copy(char to[], char from[])
    int i;

    i = 0;
    while ((to[i] = from[i]) != '\0')

Here is the error I get when I try to compile the program using Ubuntu 11.10:

cc     word.c   -o word
word.c:4:5: error: conflicting types for ‘getline’
/usr/include/stdio.h:671:20: note: previous declaration of ‘getline’ was here
word.c:26:5: error: conflicting types for ‘getline’
/usr/include/stdio.h:671:20: note: previous declaration of ‘getline’ was here
make: *** [word] Error 1

Just to make sure it wasn't a problem with the print in the book, I referenced this set of answers to back of chapter exercises from the book ( and I get a similar error when I try to run exercises 18, 19, 20, 21, etc., from that link. It's really hard to learn when I can't run the programs to see how they output. This issue started when introducing character arrays and function calls in one program. I'd appreciate any advice on this issue.

The conflicting function getline() is a GNU/POSIX extension.

K&R state that they address specifically ANSI C in their book (c.f.), which does not provide this function.

The authors present the complete guide to ANSI standard C language programming.

In order set gcc into "K&R compatibility mode" you can specify the ANSI or ISO modes for compilation. These are intended to disable compiler extensions, e.g., the function getline(). This could eventually eliminate the need to edit other examples provided by K&R as well.

For example, the following compile just fine:

$ gcc test.c -ansi
$ gcc test.c -std=c89

(Except that they complain about the implicit default return type of main() with -Wall.)

Apparantly on some systems, these modes may not work as presented here (apparantly some version(s) of Mac OS fail to correctly disable all extensions). I tested this successfully on my machine:

$ gcc --version
gcc (GCC) 4.7.2 20121109 (Red Hat 4.7.2-8)
Copyright (C) 2012 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO

I am learning programming. I plan on learning C and Objective-C this summer. I bought the C for Dummies book but it is a complete waste of time. It's way too many pages! Are there any good books I should read? Or should I just learn C from websites? What would be the fastest way because I really want to learn it fast and start learning Objective-C too.

Thank you

Also, how long does it take to learn C? Until I move to Objective-C 2.0

Stanford University posts online the lectures, class notes, and assignments for CS193P (an iPhone development class). If you don't know C or Objective-C at all, it might be tough, but I highly recommend this if you intend to do iPhone development.

I think I've read every Cocoa and Objective-C book out there, and most enjoyed Aaron Hillegass' Cocoa Programming for Mac OS X.

For learning C, I highly recommend Learn C on the Mac, by Dave Mark. Not only is it aimed at beginners, but it also teaches you a lot about the important fundamentals of programming and computer science (e.g. data structures, recursion, etc.). It's very accessible, well-written, and easy to read. Plus, I found the examples engaging and interesting to work with. After that, if you really want to solidify your foundations in C, I'd recommend trying to moving on to The C Programming Language. It's a challenging book, so take it slowly. If you find yourself having too much trouble with it, I'd say you can just skip to Objective-C, and then come back to The C Programming Language later, once you've gained more familiarity with programming in general.

A lot of people will probably recommend The C Programming Language (a.k.a. "K&R") as your first book to read on C. No doubt it is a very well-written C book (and it's short too—only around 200 pages), but I'd say it'd be a little intimidating as a 12-year-old's first exposure to C: it's pretty dense and hardcore. You can tell that it's definitely aimed at an older audience with a strong background in computers/engineering. But nevertheless, if you already know the basics of programming, reading K&R will give you invaluable insight and understanding of C. You should definitely read it at some point in your programming endeavors.

Anyways, for Objective-C, if there's only one book I could recommend, it would most definitely be Cocoa Programming for Mac OS X, by Aaron Hillegass. It's really not that long (~400 pages or so, although I'd reckon that a lot of that is due to the number of illustrations in the book), and you can get some pretty cool projects up and running in an afternoon. It's very clear and easy to read, the examples are practical and interesting to follow, but most importantly, it's got this right blend of not being too intimidating while still managing to provide you with solid information. Plus, it'll teach you more than just Objective-C: I found that I had learned some very useful design patterns, for example, by learning how some of the components of Cocoa worked.

Possible Duplicate:
Should I learn C before learning C++?

As a professional (Java) programmer and heavy Linux user I feel it's my responsibility to learn some C (even though I may never use it professionally), just to make me a better coder.

Two questions :

  1. Should I try C or C++ first - I realise they are different languages with some common ground. Is it useful to learn a bit of both, or just try one? I hear C++ is a bit of a nightmare behemoth of a language.

  2. What are the best resources (books, tutorials, practice programs, reference code) for a Java developer like myself.


Regarding (1), I'd probably say C. It's a lot more foreign. Since your goal is to be multilingual for its own sake, moving towards a language that is much different than Java will probably be more useful than learning C++, which will probably make you angry. C++ gets a lot of crap from people, and it's not necessarily awful, but the primary reason is that it is trying to force a new paradigm into the structure of C, which doesn't work as well as a language that starts with that paradigm in the first place.

For (2), I would highly, highly recommend K&R. It assumes some programming familiarity, is brief, to the point, but also is deep enough to explain concepts. It doesn't include exercises, however, which you'll have to find elsewhere. I learned C on the job, I'm afraid (and still paying for it!) so I can't give you educated help there.

For OOP languages, there are many books describing how to design software, and design patterns are mainly for OOP languages.

I am wondering whether there are any books/good articles teaching how to use C in a big project, like it is a good practice to use static functions when this function is only used in a single file.

You must read Expert C Programming by Peter van der Linden.

alt text

Code Complete 1st Ed by Steve McConell is more oriented towards C, that may be worth a look as well. At any rate his books are great reading for any professional programmer.


While heavily focused on C++, John Lakos's excellent book "Large-Scale C++ Software Design" has a lot of information that is very relevant to the design of software written in C.

Edit: Oooh. After seeing @Jackson's suggestion for the excellent "The Practice of Programming" I'd also highly recommend Eric Raymond's excellent book "The Art of UNIX Programming.". Thanks for the reminder @Jackson.



  1. C FAQ
  2. K & R
  3. Linux kernel source code

Is it advisable to directly jump onto C# with knowing just a mere bit of C (just some basics) or even may be without knowing C ?

Might as well read "The C Programming Language" by K&R because it's a quick read, and it will give you a background that may help with understanding performance going on behind the scenes in a garbage collection language.

I'm trying to find a least-resistance path from C# to C++, and while I feel I handle C# pretty well after two solid years, I'm still not sure I've gotten the "groove" of C++, despite numerous attempts.

Are there any particular books or websites that might be suitable for this transition?

About two years ago, I made the switch from C# to C++ (after 10 years of writing java). The most useful book for me was Bruce Eckel's Thinking in C++ [AMZN]. You can also read the book online at Eckel's website. It's a well-written book--the kind you can read in bed--that's also useful as a keyboard-side reference. It assumes a significant level of comfort with OO and general programming concepts.

Stroustrup [AMZN] is invaluable as a reference, but basically impenetrable unless you're trying to answer a very specific question--and even then, it's a struggle. I haven't cracked my K&R [AMZN] in a few years. I don't think it's got much value as a C++ reference. Myers' Effective C++ [AMZN] (and, once you get there, Effective STL [AMZN]) are fantastic books. They're very specific, though (e.g., "36. Design functor classes for pass-by-value"), and hence not as useful as Eckel for making the transition.

My experience writing C++ after many years writing managed languages has been great. C++ is a hundred times more expressive than C#, and extremely satisfying to write--where it's warranted. On the other hand, on the rare occasions when I still get to write C#, I'm always amazed by how quickly and succinctly I can get things done.

Anyway, Eckel's Effective C++ can help you make the transition. There's a second volume that's good, but not as good. Stick with the original.

Good luck!

You should read one of the other books posted, but then also The Design & Evolution of C++. It helps you to get inside the head of what the language is trying to do.

I'm a relative beginner to C and I need to learn how makefiles work and I'm a bit confused on how the combination of C files work. Say we have a main.c, a foo.c, and a bar.c. How should the code be written so that main.c recognizes functions in the other files? Also, in foo.c and bar.c, is all of the code written in the main function there or do we need to write other functions for what we need them to do? I've read tutorials on how makefiles are written, and it makes sense for the most part, but I'm still a bit confused on the basic logistics of it.

Make has little to do with the structure of a C program. All make does is define a dependency tree and execute commands when it finds the dependencies are out of whack. My saying, in a makefile:

foo.exe : foo.c bar.c baz.c

simply sez: foo.exe is dependent on foo.c, bar.c and baz.c. This, sotto vocce, gets expanded, using make's default rule set, to something like:

foo.exe : foo.obj bar.obj baz.obj

foo.obj : foo.c

bar.obj : bar.c

baz.obj : baz.c

Make simply walks the dependency tree starting at its root (in this case, foo.exe). If a target doesn't exist or if one of the objects upon which it depends is newer than the target, the associated commands are executed. to make the dependency correct.

See Managing Projects with Make from O'Reilly for more than you probably want to know.

As far as the second part of your question goes, the answer is just two letters: K and R. Their The C Programming Language is arguably one of the best computer programming books ever written.

alt text

I know a bunch of scripting languages, (python, ruby, lua, php) but I don't know any compiled languages like C/C++ , I wanted to try and speed up some python code using cython, which is essentially a python -> C compiler, aimed at creating C extensions for python. Basically you code in a stricter version of python which compiles into C -> native code.

here's the problem, I don't know C, yet the cython documentation is aimed at people who obviously already know C (nothing is explained, only presented), and is of no help to me, I need to know if there are any good cython tutorials aimed at python programmers, or if I'm gonna have to learn C before I learn Cython.

bear in mind I'm a competent python programmer, i would much rather learn cython from the perspective of the language I'm already good at, rather than learn a whole new language in order to learn cython.

1) PLEASE don't recommend psyco

edit: ANY information that will help understand the oficial cython docs is useful information

Learn C! (Sorry -- irresistible.)

Seriously, though, it seems like you mostly need to know about C variable types (C types, if you will) in order to use cdef effectively.

Later on, if you do decide to bite the bullet and learn C properly, treat yourself to a copy of Kernighan and Ritchie, or K & R, available on Amazon.

I'm a Perl5 programmer for 7 years and I'm trying to learn C++ now. Some of the C++ syntax is hard for me to understand and to think in C++ way.

For example: In Perl, you can mix the data in the arrays

@array = (1,"string",5.355);

You can assign any value to a scalar variable:

$var = 1;
$var = "string";
$var = \$reference_to_scalar;

There are many examples.

A friend of mine recommend me the book "Thinking of C++" by Bruce Eckel, but I haven't any C background and it's hard for me to understand some things.

So my question is - could you recommend me a book for this situation. I don't want to learn C. I understand OOP (I'm getting more familiar with C++ oop aswell), I understand the point of the pointers (and some arithmetic) and references (widely used in Perl).

I don't need manuals for dummies (what is int, bool, double, if, while), I just need a direction how to learn C++ from the perspective of a Perl programmer, because I'm sure that there are many like me.

Thank you in advance.

EDIT: Thank you for all the recommended books and the answers, I will try with "Accelerated C++". I will start from the beginning and try to change my mindflow to C++. I have added the "beginner" tag.

Actually, since you already know an imperative language, learning C won't take you much time at all. The basics are all the same -- if statements, while loops, for loops etc. Even the way the namespaces are organized are similar (although the guts of course are different.) You might want to gloss over some of the pointer handling, as C++ does references a little differently, but you would not be doing yourself any harm by picking up and reading through a copy of K&R (the official C reference) at least once. (Every decent programmer should have a copy on his bookshelf as a reference, anyway.)

After that, pick up a recent edition of Stroustrup and have at it, ensuring that you work through the exercises. Some of the concepts may be a little foreign to a Perl-oriented mind, but it won't be too strange. If you encounter a particular concept you find tricky, post again on SO and there will be lots of people happy to go through it with you!

K&R Stroustrup

I vaguely recall seeing this before in an answer to another question, but searching has failed to yield the answer.

I can't recall what is the proper way to declare variables that are pointers. Is it:

Type* instance;


Type *instance;

Although I know both will compile in most cases, I believe there are some examples where it is significant, possibly related to declaring multiple variables of the same type on the same line, and so one makes more sense than the other.

I prefer the following style:

Type *pointer;

Why? Because it is consistent with the mindset the creators of the language tried to establish:

"The syntax of the declaration for a variable mimics the syntax of expressions in which the variable might appear."

(The C Programming Language by Brian W. Kernighan & Dennis M. Ritchie, ansi c version, page 94)

It's easy to write FORTRAN in any language, but You always should write [programming language X] in [programming language X].

I've studied C programming in college some years ago and have developed some medium applications back then (nothing serious). Now I have to develop some more 'advanced' C applications (involving POSIX threads and RPC), but right now I'm a little rusty even with the basics.

Can anyone recommend me good online C reference manuals? This may help me get in tune faster.

It's not online, but hands down the best C reference is Harbison & Steele (yeah - it's better than K&R).

You can get the 4th edition for basically shipping (I don't know what improvements were made in the 5th ed.):

The best C reference by far is Kernighan and Ritchie's "The C Programming Language" in it's dead tree form. It's compact and complete.

For an online reference, you might try Brian Kernighan's Programming in C Tutorial.

I would recommend reading through the comp.lang.c FAQ at least once to help get the rust off. For reference material, you might want to grab a copy of the C Standard, the latest version of C99 with TC3 included is available for free here, for C89 the last draft version is available as a text file or you can pick up a copy of the The Annotated ANSI C Standard for a few bucks and have a hard copy of the actual standard (just ignore the "annotations" on the right-hand pages). Since you are using POSIX you might want to become more familiar with the Single Unix Specification which includes the Standard C library as well as the POSIX functions, you can read/download SUSv3 at the Open Group (registration required but free and quick).

For an offline resource I would also recommend C: A Reference Manual (5th Edition) by Harbison & Steele, it thoroughly covers every language feature and standard function of C and documents differences between the various standard versions.

I have been learning C++ for three months now and in that time created a number of applications for my company. I consider myself fairly comfortable with C++ / MFC and STL, however I don't just want to be an OK programmer, I want to be a good programmer. I have a few books on best practices but I was wondering if anyone could suggest reading materials that helped them and any disciplines which should be encouraged?


You can check out the Boost library and a number of the books written about it. While this may not have been what you had in mind, IMO, the Boost libraries are examples of well-designed modern C++ libraries that use the features of the language in pretty much the way they should be used to create among the most effective solutions for their problem domain. Granted of course, there are bizarre libraries like preprocessor and MPL which make you wonder if you'll ever have any use for them, but they're all round quite good. From my own experience, exploring the library and its literature has given me insight into how C++ can be used effectively.

Boost Beyond the C++ Standard Library: An Introduction to Boost

For C++, Scott Meyers books are very good, and will help take you to the next level.

If you don't already have it C++ by Bjarne Stroustrup, 3rd Edition

3 months into c++ and you're already comfortable with it? Sheesh, I've been learning c# for over a year and have taken numerous Microsoft courses and I'm nowhere near comfortable with it.

That being said, you'll hear Code Complete tossed about as a very good book. I'm in the process of reading it now.

I lot of folks can suggest more modern, up-to-date books. But I still recommend The Annotated C++ Reference Manual by Margaret A. Ellis & Bjarne Stroustrup.

The ARM was published back in '90. It's become somewhat outdated with respect to templates. STL is (obviously) absent. (Though the website at does a good job of covering STL!)

However, the ARM is dirt cheap (used). (Shipping will exceed the cost of the book.) Its signal-to-noise ratio remains off the scale. It's very good at digging into C++'s dirty areas, explaining what was done & why.

I still use it as a reference. I rank it up there with K&R.

Good blogs: Guru of the Week, and all the books by Herb Sutter. Those will give you quite a lot to chew already.

Modern C++ Design by Alexandrescu if you want to get a good feel for what you don't yet know, and probably don't want to know.

Code Kata's for practice!

As I see, nobody mentioned Bruce Eckel brilliant books "Thinking in C++". IMHO, it`s one of the best books to start your C++ development from. From my point of view, first volume is more helpful that the second, but both of them worth reading.

In C: How do you find the number of elements in an array of structs, after sending it to a function?

int main(void) {
  myStruct array[] = { struct1, struct2, struct3, struct4, struct5, struct6 };
  printf("%d\n", sizeof(array));
  printf("%d\n", sizeof(array[0]));
void f(myStruct* array) {
  printf("%d\n", sizeof(array));
  printf("%d\n", sizeof(array[0]));

For some reason the printf in main shows different results than the printf in f. My need is to know how many elements are in the array.

As the C reference says, you cannot do this unless either the last element is unique or you pass a count of array elements to the function.

I know that C++ has the concept of objects but C doesn't. I also know that pretty much all there is to know about C fits into K & R but the C++ library is vastly more complex. There have got to be other big differences though.

What are the major differences between C and C++?

Check out Stroustrup's FAQ here, specifically:

What is the difference between C and C++?

C++ is a direct descendant of C that retains almost all of C as a subset. C++ provides stronger type checking than C and directly supports a wider range of programming styles than C. C++ is "a better C" in the sense that it supports the styles of programming done using C with better type checking and more notational support (without loss of efficiency). In the same sense, ANSI C is a better C than K&R C. In addition, C++ supports data abstraction, object-oriented programming, and generic programming (see The C++ Programming Language (3rd Edition)"; Appendix B discussing compatibility issues is available for downloading).

Is there such a thing as dangerous knowledge when just starting out learning C or C++? In other words what is the likelihood that I could "accidently" write and compile a code snippet that formats the hard drive, renders the OS unusable, or worse case scenario silently deletes random files on the computer?

Stuff like the veritable

format C:/


rm -rf /

If I am just starting out tinkering with low level C code or even messing with libraries what are some basic things to be aware of?

If there are in fact these potential dangers lurking what is a good strategy for keeping the dev environment sandboxed from your day to day system? Are certain areas of tinkering better left to a virtualized environment?

No need to go into explicit code examples, but more general advice is what I am curious about.

I suppose a good rule of thumb is: Be sure you have an understanding of the code before you compile and run some random code snippet you find on the web.

Note: I am on OS X if that is relevant.

I recognize that there is no substitute for a good backup system. Hack away destroy your computer, at most you lose a day or hours work and have to restore.

Honestly, I think you answered your own question when you said it's a good idea to verify/understand the code that you run from the web. If you buy yourself a respectable book like The C Programming Language, the chances of you making a mistake serious enough to totally destroy your computer are slim to none. You'd really have to know what you're dong to write code that destroys your system. You're far more likely to accidentally rm -rf / when you run as root or install some kind of bad library that affects system stability.

On a side note, I strongly recommend learning C before learning C++. Otherwise, you'll spend your time learning C without being able to understand the concepts of object oriented programming.

I'm trying to learn C by reading this book. I have some programming experience but not with C.

I'm currently in Chapter 1. I have the following code:

  float f;
  for (f = 0.0; f <= 3; f += 1.1)
      printf("A: %3f B: %6.2f\n", f, f + 0.15);

It prints the output:

A: 0.000000 B:   0.15
A: 1.100000 B:   1.25
A: 2.200000 B:   2.35

Looks fine.

Now I change the printf as follows:

printf("A: %3d B: %6.2f\n", f, f + 0.15);

The new output is

A:   0 B:   0.00
A: -1610612736 B:   0.00
A: -1610612736 B: -625777476808257557292155887552002761191109083510753486844893290688350183831589633800863219712.00

What's going on here? I would expect the float to be converted to int because I used %d but that's not what happened. Also, why did the the value B go wrong as well? What happened to f here?

When you called:

printf("A: %3d B: %6.2f\n", f, f + 0.15);

C automatically converts the float values to double (it is a standard conversion made when you call a function that takes variable arguments, such as int printf(const char *fmt, ...);). For sake of argument, we will assume that sizeof(int) is 4 and sizeof(double) is 8 (there are exceptions, but they are few and far between).

The call, therefore, has pushed a pointer onto the stack, plus an 8-byte double for f, and another 8-byte double for f + 0.15. When it is processing the format string, the %d tells printf() that you pushed a 4-byte int onto the stack after the format string. Since that is not what you did, you have invoked undefined behaviour; whatever happens next is OK according to the C standard.

However, the most likely implementation blithely reads 4 bytes and prints them as if they were an int (it trusts you to tell it the truth). Then it comes across the %6.2f format; it will read 8-bytes off the stack as a double. There's an outside chance that this would cause a memory fault for misaligned access (it would require a 64-bit machine with a requirement that double be aligned on an 8-byte boundary, such as a SPARC), or it will read 4 bytes from f and 4 bytes from f + 0.15, putting them together to create some rather unexpected double value -- as your example shows.

I've been writing Java professionally for the last 5 years. Recently, I've had to dig into JNI a bit to call some Windows specific functions.

This experience has highlighted my poor command of the C (or C++ for that matter) language. My only introduction to C was a brief "dummies" book that I read in high school 11 years ago.

I know that both languages have advanced in that time frame, especially C++ and the standard library.

Would it be appropriate for me to learn C or C++? Which books would be best?

Do folks also have any recommendations for Windows programming as well? I can read through MSDN well enough to figure out certain API calls but I have a feeling I'm missing things in regards to the "big picture".


This really depends on your strengths and weaknesses. If you really like design patterns, then I'd suggest using C++, but if you just have to implement a couple simple methods in JNI, then I would recommend C. Learning C before C++ should give you a better understanding of memory management without having to worry about some of the complexities of C++ (constructor call order, destructors, and other differences between C++ and Java).

I would suggest "The C Programming Language" by Kernighan and Ritchie as the definitive manual for learning C.

If you're on a *nix system, there's ample documentation in the manpages for different functions. For example,

bash$ man malloc

I guess it depends on your objectives.

If you want to get closer to the machine, then C.

If you want to supplement you knowledge of a OO Java-like layer above C, then C++.

Accelerated C++ (sanitised Amazon link) is an awesome book to learn C++ from the point of view of C++ and not just C with other bits tacked on,

And K'n'R C (sanitised Amazon link) is still the way to go for learning C IMHO!

BTW For C++ follow up with the wisdom of Scott Meyers in the Effective C++ books! And his Effective STL book as well.




I come from a PHP based background and my new years resolution was to listen to Joel and learn C.

I am using a Windows based PC and I don't mind programming that's focused a little on the Windows side though I will be starting with console applications.

  • What compiler could I use and why?
  • What IDE could I use and why?
  • What other tools are useful for a beginner C programmer?
  • Are there free online guides?

I tried to look for SO questions but the C tag has no good questions on the Hot list but if you know of some good SO questions that are related to this one, don't hesitate to add it here below.

SO Posts

After K&R (aka The Bible in my CS class), I would recommend this book: link text It covers some of the tricky parts of C and is very well written. And you even get a certificate of completion. How could you beat that!

I'll answer your questions in order:

  • What compiler could I use and why? - Generally, gcc on the Unix world, and since you said you don't mind Windows, the latest version of MSVC (2008). though it doesn't support C99. (Remember to change the project settings to compile as C.)
  • What IDE could I use and why? - I've heard good things about Eclipse, but I never got much into it since I'm on Windows, and gcc options for Windows are... not stellar. MSVC 2008 is good, but Intellisense doesn't quite live up to C#, though it isn't as important in C as in C++. I've heard they're fixing this for 2010.
  • What other tools are useful for a beginner C programmer? - Turn up your warning level to the maximium supported by the compiler. (To a reasonable standard.) This will help you mantain good coding practices.
  • Are there free online guides? - Yes. I don't know of any very good ones though. Get K&R 2nd Ed. It's an awesome book, and short too, by the creators of the language.

And another bit of advice: Try to stick to, and learn, standard ANSI C first, stay away from proprietary extensions.

I'm a programming student with two classes in C#, but I'm just taking my first class in C++, and thus I'm being exposed to pointers.

I know how they work, and the proper way to use them, but I wondered about some of the ways that professional programmers use pointers in their programs.

So how do you use pointers? Or do you?

This will help me understand some practical applications for pointers, so thanks!

If you have some time on your hands for reading a book, I would recommend reading The C Programming Language which makes heavy use of pointers.

A simple example of a standard function:

/* strlen: return length of string s */
int strlen(char *s) {
    char *p = s;
    while (*p != '\0') p++;
    return p - s;

A matrix A[i][j] is given. If we want to add the elements of the matrix, which method is better and why?

  1. column wise
  2. row wise

From my point of view, row wise is better because in array representation elements are stored in contiguous memory locations so accessing them takes less time.But since in RAM fetching every location takes equal time, does it matter?

For C, the best way to handle multidimensional arrays is:

int a[MAX_I][MAX_J];
for (i = 0; i < MAX_I; ++i) {
   for (j = 0; j < MAX_J; ++j) {
      /* process a[i][j] */

The reason for this is that the C language handles arrays as pointers with offsets, see: The C Programming Language.

As title says, i have this code :

typedef struct Book{
    int id;
    char title[256];
    char summary[2048];
    int numberOfAuthors;
    struct Author *authors;

typedef struct Author{
    char firstName[56];
    char lastName[56];

typedef struct Books{
    struct Book *arr;
    int numberOfBooks;

I get these errors from gcc :

bookstore.c:8:2: error: unknown type name ‘Author’
bookstore.c:9:1: warning: useless storage class specifier in empty declaration [enabled by default]
bookstore.c:15:1: warning: useless storage class specifier in empty declaration [enabled by default]
bookstore.c:21:2: error: unknown type name ‘Book’
bookstore.c:23:1: warning: useless storage class specifier in empty declaration [enabled by default]

If i change the typedefs like this :

typedef struct{
    char firstName[56];
    char lastName[56];
} Author;

Then no warnings and no errors occur. Having searched through and a couple of hours googling i can't figure why the first implementation won't work.

There are several things going on here. First, as others have said, the compiler's complaint about unknown type may be because you need to define the types before using them. More important though is to understand the syntax of 3 things: (1) struct definition, (2) struct declaration, and (3) typedef.

When Defining a struct, the struct can be named, or unnamed (if unnamed, then it must be used immediately (will explain what this means further below)).

struct Name {

This defines a type called "struct Name" which then can be used to Declare a struct variable:

struct Name myNameStruct;

This declares a variable called myNameStruct which is a struct of type struct Name.

You can also Define a struct, and declare a struct variable at the same time:

struct Name {
} myNameStruct;

As before, this declares a variable called myNameStruct which is a struct of type struct Name ... But it does it at the same time it declares the type struct Name.
The type can be used again to declare another variable:

struct Name myOtherNameStruct;

Now typedef is just a way to alias a type with a specific name:

typedef OldTypeName NewTypeName;

Given the above typedef, any time you use NewTypeName it is the same as using OldTypeName. In the C programming language this is particularly useful with structs, because it gives you the ability to leave off the word "struct" when declaring variables of that type and to treat the struct's name simply as a type on its own (as we do in C++). Here is an example that first Defines the struct, and then typedefs the struct:

struct Name {

typedef struct Name Name_t;

In the above OldTypeName is struct Name and NewTypeName is Name_t. So now, to declare a variable of type struct Name, instead of writing:

struct Name myNameStruct;

I can simple write:

Name_t myNameStruct;

NOTE ALSO, the typedef CAN BE COMBINED with the struct definition, and this is what you are doing in your code:

typedef struct {
} Name_t;

This can also be done while naming the struct, but this is superfluous:

typedef struct Name {
} Name_t;

NOTE WELL: In the syntax above, since you have started with "typedef" then the whole statement is a typedef statement, in which the OldTypeName happens to be a struct definition. Therefore the compiler interprets the name coming after the right curly brace } as the NewTypeName ... it is NOT the variable name (as it would be in the syntax without typedef, in which case you would be defining the struct and declaring a struct variable at the same time).

Furthermore, if you state typedef, but leave off the Name_t at then end, then you have effectively created an INCOMPLETE typedef statement, because the compiler considers everything within "struct Name { ... }" as OldTypeName, and you are not providing a NewTypeName for the typedef. This is why the compiler is not happy with the code as you have written it (although the compiler's messages are rather cryptic because it's not quite sure what you did wrong).

Now, as I noted above, if you do not name the struct type at the time you define it, then you must use it immediately either to declare a variable:

struct {
} myNameStruct;  // declares myNameStruct as a variable with this struct
                 // definition, but the definition cannot be re-used.

Or you can use an unnamed struct type in a typedef:

typedef struct {
} Name_t;

This final syntax is what you actually did when you wrote:

typedef struct{
   char firstName[56];
   char lastName[56];
} Author;

And the compiler was happy. HTH.

Regarding the comment/question about the _t suffix:

_t suffix is a convention, to indicate to people reading the code that the symbolic name with the _t is a Type name (as opposed to a variable name). The compiler does not parse, nor is it aware, of the _t.

The C89, and particularly the C99, standard libraries defined many types AND CHOSE TO USE the _t for the names of those types. For example C89 standard defines wchar_t, off_t, ptrdiff_t. The C99 standard defines a lot of extra types, such as uintptr_t, intmax_t, int8_t, uint_least16_t, uint_fast32_t, etc. But _t is not reserved, nor specially parsed, nor noticed by the compiler, it is merely a convention that is good to follow when you are defining new types (via typedef) in C. In C++ many people use the convention to start type names with an uppercase, for example, MyNewType ( as opposed to the C convention my_new_type_t ). HTH

An example of this would be:

char str[] = "Hello";
int strLength = strlen(str);

for (   char * pc = str;
        pc < str + strLength;
    *pc += 2;

Edit: Accounted for write-protected memory issue.

Have a look at the C bible, a.k.a. K&R C (sanitised Amazon link) as they have a discussion about the advantages of both techniques.

Either way, "there be dragons ahead, arr!" so tread very carefully as the road of good pointer arithmetic intentions is paved with the abundant corpses of buffer overflow exploit victims! (-:

In fact, for an excellent discussion and a "wander out on to the thin ice of advanced pointer manipulation" (his term), have a look at Andy Koenig's excellent book "C Traps and Pitfalls" (sanitised Amazon link)

Edit: One thing I forgot to mention, is that I tend to prefer the usual "for (int i = 0; ..) style purely because it is such an ingrained idiom that anyone can see what you're doing with a quick glance. Using pointer arithmetic requires a bit more of a deeper look.


I am reviewing some optimisation libraries and came across the function signature

double solvopt(unsigned short n,
           double x[], 
           double fun(), 
           void grad(),
           double options[],
           double func(),
           void gradc()

note that fun() and gard() are passed as function. My question is if this is valid standard C grammar.


Your array parameters (x and options) should probably be pointers.

Referring to a function with parenthesis, like "func()" or "gradc()" calls the function. The name of the function alone is a code pointer that can be dereferenced to call the function in question.

When in doubt, try compiling this with an ANSI C compiler - a lot of compilers provide an ANSI compatibility switch to enforce standards compliance. Also, the K&R book is your friend.

Is this a homework question?

I've got some code I'm mantaining with the following variable declaration:

char tmpry[40];

It's being used with this function:

char *SomeFunction(char *tmpryP) {
   // Do stuff.

The function call is:


I'm pretty damn sure that's just the same as:


I've even checked that the char* pointer in SomeFunction ends up pointing to the same memory location as the array in both cases.

My question is a sanity check as to whether the two function calls are identical (and therefore the original programmer was just being nasty)?

The declaration

int a[10]; int *pa;

There is one difference between an array and a pointer that must be kept in mind. A pointer is a variable, so pa=a and pa++ are legal. But an array name is not a variable; construction like a=pa and a++ are illegal

As format parameters in a function definition, char s[] and char *s are equivalent;

From: The C Programming Language 2th, Page 99-100

I've started reading "The C Programming Language" (K&R) and I have a doubt about the getchar() function.

For example this code:

#include <stdio.h>

  int c;

  c = getchar();

Typing toomanychars + CTRL+D (EOF) prints just t. I think that's expected since it's the first character introduced.

But then this other piece of code:

#include <stdio.h>

  int c;

  while((c = getchar()) != EOF) 

Typing toomanychars + CTRL+D (EOF) prints toomanychars.

My question is, why does this happens if I only have a single char variable? where are the rest of the characters stored?


Thanks to everyone for the answers, I start to get it now... only one catch:

The first program exits when given CTRL+D while the second prints the whole string and then waits for more user input. Why does it waits for another string and does not exit like the first?

It's treating the input stream like a file. It is as if you opened a file containing the text "toomanychars" and read or outputted it one character at a time.

In the first example, in the absence of a while loop, it's like you opened a file and read the first character, and then outputted it. However the second example will continue to read characters until it gets an end of file signal (ctrl+D in your case) just like if it were reading from a file on disk.

In reply to your updated question, what operating system are you using? I ran it on my Windows XP laptop and it worked fine. If I hit enter, it would print out what I had so far, make a new line, and then continue. (The getchar() function doesn't return until you press enter, which is when there is nothing in the input buffer when it's called). When I press CTRL+Z (EOF in Windows), the program terminates. Note that in Windows, the EOF must be on a line of its own to count as an EOF in the command prompt. I don't know if this behavior is mimicked in Linux, or whatever system you may be running.

I want to broaden my programming experience and so figured that learning C (not C++) would be a nice idea - I've got a starting project (some simple 2D games using SDL) and given it a go, but I have to admit I'm struggling.

Now I consider myself to be a very a competent C# developer, but C is just a completely different world!

  • No namespaces.
  • Without classes I don't know how to structure my code.
  • I understand header files & includes, but my use of them doesn't seem quite right.
  • The loss of (for example) the String class is a bit of a culture shock.

On top of that I'm finding it tricky to separate out the C++ information from the C information (for example is snprintf a C++ only thing?)

This may sound like an odd request, but are there any good guides for learning C if you have experience in other languages?

Don't try to learn C from C++ books/web sites. Start with something aimed only at C. A great place is The C Programming Language. It's the original and still one of the best programming language books out there.

Learning C is going to be a struggle because it's a different kind of language. It's a procedural language, not an object oriented language. It will be good to stretch your brain in learning it. You'll likely also learn a lot more about the way your OS works because it's down much closer to the metal.

Note also that it's a much less complex language and thus is missing a lot of the niceties of a modern language. There is no BCL/.Net Framework. As you noticed, there is no string class (although there are string functions).

I want to code drivers in C in linux os, though I think its very tough. Can I get some hints as to how to start or books to follow? Drivers can be from my USB port to graphics card!!

I know as to where I can search for books, I would like to know as to what the basic knowledge I should start with. Do I need to have hardware knowledge and which specific books are good for novice like me?

Before you jump into designing drivers you should first get exceptional C skills and probably some Linux Kernel know-how. Desigining drivers is not trivial and might scare you off if you are not used to programming on a low-level.

I might recommend The C programming Language if you are not accustomed to C as it is, in my opinion, the primer on C if you have some programming background.

Several texts:

"Linux Device Drivers" (the O'Reilley book) by Rubini and Corbet is the definitive book for Linux Device Drivers.

Cool! see the free pdf version in Roddy's answer & kristina's comment!

Can anyone provide me a very good tutorial for structures in C?

I have made google search, but I find normal information. I am looking for structures in detail. Kindly let me know.

I usually advice (and was always advised) to use official guides. For the case of ANSI C you can't get any more detailed and official than K&R2.

I became a professional programmer in the era of object oriented code, and have years of experience programming in C++. I often work on large projects that have years of legacy code in a mix of c++ and c. I feel less comfortable working on pure c parts of systems. From programming in C++ I understand all the c syntax, but there's a hole in my knowledge about how to organise a complex c program without objects, and what constitutes best practise for managing memory that I would like to fill. I learnt c++ after working as a java programmer, and think a bit more c would make me a better c++ programmer, and a bit less of a java translated into c++ programmer

You could also check out The C Programming Language ANSI C Edition written by Kernighan and Ritchie. Yes, it's old, but it only clocks in at approximately 200 pages and covers the entire language as well as the standard library.

I'm fresh out of college and have been working in C++ for some time now. I understand all the basics of C++ and use them, but I'm having a hard time grasping more advanced topics like pointers and classes. I've read some books and tutorials and I understand the examples in them, but then when I look at some advanced real life examples I cannot figure them out. This is killing me because I feel like its keeping me from bring my C++ programming to the next level. Did anybody else have this problem? If so, how did you break through it? Does anyone know of any books or tutorials that really describe pointers and class concepts well? or maybe some example code with good descriptive comments using advanced pointers and class techniques? any help would be greatly appreciated.

To understand pointers, I can't recommend the K&R book highly enough.

The following text is an excerpt from C Programming Language, 2nd Edition, written by the creator of the C language (so I presume it is correct):

Although variables of enum types may be declared, compilers need not check that what you store in such a variable is a valid value for the enumeration.

I have some doubts:

  1. For what cases in the C language doesn't the compiler check the value of an enum?
  2. enum constants are not checked for some reason. Why not? What are the reasons?
  3. Since enum is not checked by the compiler, is using enum error-prone? Please explain.
  1. An enumeration is like a fancy integer, and it's better than defining a whole load of constants or preprocessor macros as names for the constant values you want to store, because a compiler (or editor) can check that you're using the right names and values to go with the right type. On the other hand, being just an int, there's nothing stopping you putting in a value you didn't make a name for, which is occasionally useful.

  2. They can't be checked in every case. What if you add two numbers together to get the value that's going to be put in the enum-typed variable? It could be any value, generated at runtime, so it can't be checked (without a lot of overhead, at least).

  3. Everything in C is unsafe; there's practically no feature which the compiler can totally prevent you from abusing. enums are safe because they are effective at preventing programmer error and confusion, not because they stop you doing something stupid.

When do I need to insert/don't insert & for scanf() in C? Thank you.

int main()
    char s1[81], s2[81], s3[81];

    scanf("%s%s%s", s1, s2, s3);

    // If replace scanf() with the expression below, it works too.
    // scanf("%s%s%s", &s1, &s2, &s3);

    printf("\ns1 = %s\ns2 = %s\ns3 = %s", s1, s2, s3);

    return 0;

//programming is fun
//s1 = programming
//s2 = is
//s3 = fun

The arguments after the format specifier must be pointers. When an array name is passed to a function, the location of the initial element is passed, so you don't need to use the & at all in your example. You could do this though (from K&R):

int day, year;
char monthname[20];

scanf("%d %s %d", &day, monthname, &year);

Since day and year are int, you must use the & to get the address of those variables. Since monthname is an array, no & is required.

Another question. I have been researching everything this wonderful community has offered me in terms of my journey to pursue game development.

I have come to the conclusion that I would prefer to develop on my native machine, OS X - eventually leading to the iPhone.

I already own both Big Nerd Ranch guide's, Iphone Programming - the Big Nerd Ranch Guide and Learn to Program on Mac OS X - the big Nerd Ranch Guide.

My goal that I am trying to shoot for is a game similar to Blizzard's Diablo II.

When going through these books, everything seemed a bit over my head due to lack of Objective-C experience (so I suspect).

What it the best beginner friendly way for me to reach my goals? I have been looking at Objective-C books for beginners from Apress and the like, or straight C books.

How would experienced developers such as yourself guide a newbie through this path?


  • edit -

To answer why I have picked the apple route, it just looks to be the most comfortable (environment is native to the machine). I may be very wrong though. I was looking at Unity, it supports C#, JavaScript and Boo. Others like Panda3D use Python. I am just not sure, it seems like the decision process has become rather challenging.

I find that a good way to learn a new language is to start with replicating common command-line tools like wc, grep, ls, etc. This will teach you the basics of I/O (both file and stdin/stdout) and some basic string parsing, as well as other goodies here and there. Additionally, you have a deterministic method of determining whether your program does it right or not, since you can easily compare to the standard command's output or behavior.

K&R, as well as Programming in Objective-C 2.0, are good places to learn the basics of C and Objective-C.

Once you have the basics of the language down, start with basic GUI programs (the ones in Hillegass's book are a good start). Once you can hook a basic GUI on the front of some underlying logic, it's time to start thinking more seriously about your game. Hillegass's book has a basic intro to using NSOpenGLView, which you can use to manually draw in 2D and 3D. It's important to note that when going through the examples in any book, you'll want to thoroughly understand what they're doing and how they're doing it, enough so that you can make some modifications yourself to enhance/change the behavior of the sample program you're working with.

Once you understand the basics of how your underlying game logic can hook to something the user can see, it's time to go find a game/drawing library that will get you where you're going. You definitely don't want to write all of the graphics routines yourself for a game similar to Diablo.

I asked a couple of questions a while ago which have fed into this one, influencing what I want to do with my spare time:

What Language to learn to give me something different to C#

What Masters Programs are looking for

Aside from the basics, I know very little C. I want, and need, to know more C in order to be more successful at what I do, and to understand things at a deeper level.

So, my questions are:

What online resources / books would you reccommend for learning C?

Would you suggest in-person learning, if so where, and how much (London please)?

Basically, what resources should I use?

Kernigan and Ritchie is the best. Make sure it's the ANSI C version.

After that, get Guy Steele as a reference.

I loved Herbert Schildt's 'C Complete Reference' when I was starting out. Also strongly recommend K&R, a book you never outgrow as a C coder.

In my copy of C Programming Language (aka: K&R), there seems no mention of multithreading. Is the book less complete than I imagined? Did multithreading emerge after it was written? Am I thinking about this the wrong way?

Where does the concept of multithreading fit into the C world?

Edit: I think my original question have been:

  • you can write anything in C
  • multithreading exists
  • you cannot write multithreading in C <-- logical contradiction

What accounts for this contradiction? Where's the origin of multithreading? If POSIX, then what is POSIX written in if not C? A form of assembly that is inaccessible to C?

C is a pretty low level language. Support for threads in a typical C program comes from the OS, not from the C runtime - if your environment doesn't support threads, then you'll have to implement them yourself, find a library that does it, or do without threads. This is in contrast to a language like Java, where the runtime environment provides many services that are guaranteed to be available to Java programs whether or not the underlying OS supports them in the manner that the Java platform exposes.

Now, having said that, I'm pretty sure that when the first edition of K&R was published, Unix did not support threads. Since C was first implemented as a systems language for the Unix environment, it's not surprising that it has no native thread support.

If you're writing code for a Unix like environment, look for POSIX threads if you need a well supported API for implementing multithreaded programs in C.

I really want to learn C (I'm planning on joining an open source GNOME project). What would be a good tutorial?

The C Programming Language (often referred to as "K & R") is almost universally considered to be the best resource for learning C.

While "The C Programming Language" is certainly a great book and a very good introduction to the C language, it has several drawbacks:

  • It is somewhat dated, the 2nd edition (the last one) covers only C89 which is now 20 years old. While C99 (the current Standard) isn't universally supported, there are a number of features from it that are supported by many implementations and exposure to them is useful.
  • It isn't comprehensive. It doesn't cover many of the standard library functions in any detail and certain intricacies are not explored in depth.
  • The text assumes you are already an experienced programmer and has a very terse style which doesn't work well for everyone.

If you are looking for a more beginner-friendly, comprehensive, or up-to-date book, I would strongly recommend C Programming: A Modern Approach, 2nd Ed. It covers every aspect of the language and the standard library in depth, including C99, and is extremely well-written. While the list price is rather high, it usually isn't difficult to find a copy for around $60 USD.

I've been using objective C for a while now, and I've started learning some of the lower level iPhone API's such as core audio. Most of these API's are in C which is confusing me a bit, I'm not sure where to put a lot of code and I don't know the rules, etc. Does anyone know where a good place to start learning this is?

Thanks, Darren.

Does anyone know where a good place to start learning this is?

  1. Buy and read "The C Programming Language". It's not very long and surprisingly enjoyable.
  2. Read and understand Apple's C-based example code.
  3. Browse the header files for Apple's classes. This is a great way to learn how apple sets up enums and string constants, etc.

Doing these three things won't make you an expert in C, but it'll give you 90% of what you need to be able to confidently get things done with Apple's low level frameworks.

Possible Duplicate:
How-to articles for iPhone development, Objective-C

I'm looking for a career change, and am thinking about learning programming. I'm 36, reasonably intelligent, eg I'm a emergency specialist nurse, and have lots of time on my hands. Where does one begin to even find out if I should pursue this futher? What do I need to know first? Where are some good resources? I'm particularly interested in developing iphone applications as I've got some good origninal ideas that haven't been developed yet.

The best advice I can give anyone who wants to lean programming is to get a good book and dive right in. But don't just read it and memorize whats going on, understand what's happening and why things work.

Every programming book you buy will come with hundreds of examples and explanations of code, take that code and modify it in a way thats useful to your learning. An example shows you how to count the number of spaces in a sentence, great, now modify it to count a's, then vowels, then the number of letters, curiosity is king here.

I recommend The C Programming Language not only will that help you later on down the line with iPhone Development but C is one of the most popular and useful language ever created.

If you don't want to learn by books, tons of schools now put up videos of their programming courses including MIT and Stanford. Stanford even has a course dedicated to iPhone development. All these videos can be found on iTunes under iTunes U.

In addition I don't know if you're familiar with Reddit, but there is a great subreddit called CarlH Programming where someone put up interactive tutorials and explanations of introductory programming topics. The site is still active and I can honestly say even as a professional I look at it from time to time for references. Reddit Carl H Programming

And most of all, don't be afraid to ask questions either on Stack Overflow, or forums. Programmers love answering questions.

Does anyone know any good resources with tasks or problems to get practice in things that are "new" in C from the point of view of someone with experience in high-level languages like C# and PHP? All I can seem to find are more "challenges" than problems for practice.


This supposed to be C bible.

Check out The Standard C Library by P. J. Plauger, from 1991. It alternates quotes from the standard (C89, I believe) with discussion of how the library functions were intended to be used, along with a fully described implementation of the complete C standard library. Source code is included as well.

Yes, the book hasn't been updated for the latest standard, but it still has a lot of value from explaining at least some of the rationale behind some of the oddities of the standard library. Incidentally, Plauger was on the standards committee.

Plauger wrote a number of the classic books on both C and early Unix. Track down and read the oldest for a taste of pre-C history...

I'm in the process of teaching myself Objective-C via Stephen Kochan's "Programing In Objective-C 2.0" It's a great book and currently reading it for the second time, first time I got the gist of it and now it's really starting to sink in the second time.

If you have a moderate (about) knowledge of Objective-C, how difficult would it be to learn C? I realize there is seemingly endless debate on which language to learn first. I decided to go with Objective-C because I was interested in Cocoa Mac Apps/iPhone apps.

Side Note: For those familiar with the Chipmunk Physics engine... The reason I may start pursuing C eventually is that it uses C. How much C would I need to know to adequately use it. I was going to use it along with Cocos2d which uses Objective-C

I learned C before I learned Objective-C, but the two have their similarities and differences. All the if statements, for & while loops are all the same in C, but how you GTD is different. Your not really exposed to the whole pointer thing in Objective-C, but that is super important in C, and the only way to get that down is reading and practice. It may seem daunting, but once you get the hang of it, its not that bad. Functions are a bit different then methods syntactically and how their called, so you will have to learn that also, but if you get a good book ( it shouldn't be that hard. Just read up and practice!

I also highly recommend the Stanford iTunes-U programming paradigms class, helps a lot learning about pointers, after you have a basic knowledge! Being a young programmer, it definitely helped me get a good grasp of it all.

In Dennis Ritchie I found this,

struct rect r , *rp = r;

then these four expressions are equivalent :

  1. r.pt1.x
  2. rp->pt1.x
  3. (r.pt1).x
  4. (rp->pt1).x

because operators associate left to right.
Shouldn't it be struct rect *rp = &r?

It was a typo in the book, and it's been corrected in later editions.

The book in question is "The C Programming Language", 2nd Edition, by Kernighan and Ritchie, commonly referred to as "K&R2". It's not generally referred to as "Ritchie", since he was just one of the two authors. (Some of you might be interested in knowing that it's now available as a Kindle e-book.)

The errata list for the book says:

A later printing in October, 1989, made minor changes on page 131(§6.2) to add & to the last example ( struct rect r, *rp = &r;), on page 208(§A.17) to change "equal" to "unequal" in the description of logical OR, and on page 254(§B.8) to clarify that for automatics variables, only those declared volatile are restored to their latest values after a setjmp / longjmp sequence.

(And yes, the phrase "automatics variables" should be "automatic variables".)

It is a university task in my group to write a compiler of C-like language. Of course I am going to implement a small part of our beloved C++.
The exact task is absolutely stupid, and the lecturer told us it need to be self-compilable (should be able to compile itself) - so, he meant not to use libraries such as Boost and STL.
He also does not want us to use templates because it is hard to implement.
The question is - is it real for me, as I`m going to write this project on my own, with the deadline at the end of May - the middle of June (this year), to implement not only templates, but also nested classes, namespaces, virtual functions tables at the level of syntax analysis?
PS I am not noobie in C++

I will like to stress a few points already mentioned and give a few references.


2) Don't worry, with proper guidance, good organization and a fair amount of hard work this is doable.

3) Read the The C Programming Language cover to cover.

4) Understand important concepts of compiler development from the Dragon Book.

5) Take a look at lcc both the code as well as the book.

6) Take a look at Lex and Yacc (or Flex and Bison)

7) Writing a C compiler (up to the point it can self compile) is a rite of passage ritual among programmers. Enjoy it.

What is a good first programming language. The only programming I did was try to learn Objective-C. And I need to be able to access it on linux or mac so I think that means no Visual Basic or C# and must be useful. I forget I have all the time in the world.

I learnt Python as my first language, however I wish I hadn't as it is far too easy. If you are dedicated, learn something tricky - like C or C++. If you learn an easier language like PHP or Ruby or Python, you'll find it much harder to learn languages that don't do everything for you.

If you learn the easier languages afterwards, you'll come to appreciate them, not take them for granted.

So my recommendation would be C. It's tricky but if you're dedicated, you'll do well.

If you want something a bit more easy going, I'd go with PHP (if you want to get into web related stuff) or Python (can be used for the web but mainly isn't - that's more of a general-purpose language).

Python is a great language which I heartily recommend. Here's a good start:

If you want to learn C, get a copy of K&R's guide: - One of the best programming books ever written.

Just to define, by the way - a 'harder' language is a lower-level language. It's less abstracted away from the hardware so potentially a bit trickier to understand. However this means it's more powerful and it performs a lot faster. A higher level language (such as Python, Java or Ruby) has more real-world concepts (e.g. the concept of an 'object') and a lot of nice, convenient functions. However there is a performance trade-off. The higher level a language is, the more performance (in most cases at least) suffers.

There are advantages of both types of language, but here's one way of putting it: lower level languages pay better ;)

Would it be better to learn C before learning any type of WEB and desktop programming?

I don't know how to program, I want to learn Javascript and my friends suggested to me that I should learn C first.

I actually think that JavaScript is one of the best languages to start programming with. Later, when you you really get it and you want to go deeper, C is something great to know. It gives you a much deeper understanding of how computers really work.

JavaScript really lets you get started fast, see immediate results, and ramp up to more complex concepts very fluidly.

The rest of my answer assumes you know practically nothing about programming - web or otherwise. Maybe you know a little html basics.

Open up a text editor. You can even just start with notepad or something. And put in the following:

            alert("Hello, World!");

Save the file as hello.html and open it in a browser. Poof! You've written a program. Doesn't get easier than that. No need to get into the command line or download or build anything. I remember when I first started being frustrated trying to get PHP running on my machine and wishing it was as simple as getting started with JavaScript.

The next step is just to read and explore. Documentation is freely available all over for learning more. I highly recommend anything from Douglas Crockford and JavaScript:The Definitive Guide.

A pretty good basic project would be a calculator program, but there's lots of fun things you can do. When you've gotten your feet wet, and you feel a little more confident, explore some other languages. Ruby is a pretty good step from JavaScript. By that point you'll probably know where to go yourself. You may never take the road to learning C. Even if you learn it, you will likely never really have to use it.

I think it depends on your motives - are you aiming to become a professional programmer? If so, there could be some value in learning C first.

Most entry-level programming subjects at University are taught in terms of C; it can give you a deeper insight into how software works. Also, K&R is a valuable programming manual in its own right.

If your aim is to create a simple set of DHTML pages, then by all means, jump straight into JavaScript. However, I think C can offer you a lot, if you're serious about programming.

C99 and C11 support wchar_t and multibyte functions .But I am not sure about ANSI C (1989).

Is it correct that wchar_t and multibyte functions (mblen, mbstowcs, mbtowc, wcstombs, wctomb) are part of ANSI C?

I don't find these functions in Kernighan and Ritchie book (C Programming Language (2nd Edition)).

The name wchar_t is in the C89 (and C99) standard(s), but it is not a langauge-supported type. It is a typedef for some integer type capable of holding the requisite number of bits. C89 7.1.6 [Standard Definitions ] says:

which is an integral type whose range of values can represent distinct codes for all members of the largest extended character set specified among the supported locales; the null character shall have the code value zero and each member of the basic character set defined in 5.2.1 shall have a code value equal to its value when used as the lone character in an integer character constant.

This means that someone can define wchar_t to be whatever they want in C89 so long as <stddef.h> has not been #included.

In C++, this is illegal; wchar_t is a keyword in that language.

As for the multibyte functions you referenced, they appear to be part of C89. Section 7.10.7 [Multibyte character functions] defines mblen, mbtowc, wctomb, and 7.10.8 [Multibyte string functions] defines mbstowcs, and wcstombs (all in <stdlib.h>). Note of course that because C89 does not have const that the const-qualified versions of these functions are not available.

for example in this code:

double **Data, *DataT;
Data = (double **)malloc(3*sizeof(double *)+3*12*sizeof(double));

I just read that malloc allocates memory from the heap. But i could not find what that (double **) meant in front of the malloc. There is a line of code directly after this as well that i have seen this in.

for (i = 0, DataT = (double *)(Data+3); i < 3; i++, DataT += 12)

Here there is a (double *) in front of Data+3

Could you please explain to me what that does? Thank you

It's a type cast. The rules for its syntax and usage should be a part of any C primer. The definitive book for this kind of thing is the one by Kernighan and Ritchie.

How do you create a new malloc() function defined in C language ?

I don't even have an elflike hint as to how to do this , how to map virtual space address with physical space , what algorithm to follow ? I do know that malloc() is not so efficient as it can cause fragmentation. So something efficient can be created. Even if not efficient , how to implement a naive C malloc function?

It was asked recently in an interview.

I think it's a nice example of malloc in An example in Chapter 8.7 of C Programming Language book:

I know several programming languages including Objective-C, Java, C#, and python, and C. However, I need to brush up my efficiency in C.

In most languages that happen to be high-level, object-based, and GUI-oriented, I create a few standard object-oriented examples to orient me to the language/framework. I usually create a "car" example where I model a car and allow the user to adjust the speed, watching the mileage increase.

However, something tells me this example is not as practical to carry over to C in a unix command-line setting. What are some good basic ideas to 'test myself' in a unix command-line based C setting?

Thanks for any input!

EDIT: Thanks for the answers. My basic concern with the car example is that I shouldn't be attempting object-oriented in this environment, but rather do something that is more suited to the language. Thanks to Duck for the suggestion of recreating command line utilities.

Get yourself a copy of

C Programming Language (2nd Edition)

I'm a PHP developer, and I use the MVC pattern, and object oriented code. I really want to write applications for the iPhone, but to do that I need to know Cocoa, but to do that I need to know Objective-C 2.0, but to do that I need to know C, and to do that I need to know about compiled languages (versus interpreted).

Where should I begin? Do I really need to begin with plan old "C", as Joel would recommend?

Caveat: I like to produce working widgets, not elegant theories.

Get Cocoa Programming For Mac OS X by Aaron Hillegass. This should get you on your way to Cocoa programming. You can look up C-related programming as things come up.

K&R C Programming Language is the definitive reference that is still applicable today to C programming.

Get the Cocoa book, work though it and if you encounter any snags, just ask your C questions here :)

Yes, you're really best off learning C and then Objective-C. There are some resources that will get you over the C and Objective-C language learning curve:

And there are some resources that will get you over the framework learning curve:

Despite what Jeff might say, learning C is important for professional software developers for just this reason. It's sort of a baseline low-level lingua franca that other innovation happens atop. The reason Jeff has been able to get away with not learning C is not because you don't need to know C, but because he learned Pascal which is in many ways isomorphic to C. (It has all the same concepts, including pointers and manual memory management.)

No need to start with plain C. Start with an excellent book instead: Cocoa Programming for Mac OS X.

I’m having some problems learning C and I really have no where else to turn for advice. I come from a list of OOP languages such as JavaScript and mainly Python, so C is a major change and I’m hitting quite a few bumps trying to learn the fundamentals. I initially started with Zed Shaw’s “Learn C the Hard Way”, but he doesn’t really teach anything in the book. Yeah, he makes you write a lot of code and change stuff up, but I’m not learning why the code works and it is just leading to more confusion as the examples build in complication.

The main problems I am having are the difference between variables and pointers (I thought it was pretty distinct until I saw some examples that I’ll be posting below, which completely blurred the line between the two).

For example, I understand that declaring and initializing an int called a and a pointer, p would look like this:

int a;
int *p;

a = 12;
p = &a;

What confuses me is when you declare variables that look like pointers, but aren’t really pointers at all (or are they?). For example:

char *string = "This is a string";
printf("%s\n", string);

What is string when it is defined and initialized? Is it a pointer? And if it is, why don’t you dereference it when printing it in the printf function? There are many examples like this that confuse me.

Another example I came across that made no sense whatsoever:

int i;
scanf("%d", &i);

How does this function update the value of integer i, when the ampersand is supposed to reference the location in memory of the variable, not the value? It gets even more complicated with arrays and structs, which is where I stopped and decided I needed to find some advice.

I honestly feel embarrassed posting such a noob question, but everyone starts somewhere. These fundamentals are something I know I need to be able to understand before moving on, but it is so hard for me to make sense of it when I see examples of code that contradict what I had just learned. I know this is a very general question but I am hoping some of you could either explain these basics or point me in a direction where I can better learn/understand this. Most video tutorials I have come across are too general and same with the text tutorials online, where they tell you how to do something, but don’t explain it, which causes some serious problems down the line.

    char *string = "This is a string";
    printf("%s\n", string);
What is string when it is defined and initialized? Is it a pointer? And if it is, why don’t you dereference it when printing it in the printf function? There are many examples like this that confuse me.

First, a little background:

Except when it is the operand of the sizeof or unary & operators, or is a string literal being used to intialize another array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and the value of the expression will be the address of the first element of the array.

The string literal "This is a string" is an expression of type "17-element array of char" (16 characters plus the 0 terminator). Since it is not the operand of either the sizeof or unary & operators, and since it isn't being used to initialize an array of char, the type of the expression is converted to "pointer to char", and the value of the expression is the address of the first element.

The variable string is declared as type "pointer to char" (char *), and it is initialized with the address of the string literal.

In the printf call, the conversion specifier %s expects its corresponding argument to have type char *; it will print characters starting at the specified address until it sees a 0 terminator. This is why the variable isn't dereferenced in the printf call.

    int i;
    scanf("%d", &i);
How does this function update the value of integer i, when the ampersand is supposed to reference the location in memory of the variable, not the value? It gets even more complicated with arrays and structs, which is where I stopped and decided I needed to find some advice.

C passes all function arguments by value, meaning the formal parameter in the function definition and the actual parameter in the function call are two different objects in memory. Updating the formal parameter has no effect on the actual parameter. For example, imagine a simple swap function, like so:

void swap( int a, int b ) { int tmp = a; a = b; b = tmp; return; }
int x = 0, y = 1;
printf( "before swap: x = %d, y = %d\n", x, y );
swap( x, y );
printf( " after swap: x = %d, y = %d\n", x, y );

If you compiled and ran this code, you'd see the same values for x and y in both output statements; a and b are different objects in memory from x and y, and changing the values of a and b has no effect on the values of x and y.

Since we want to modify the values of x and y, we must pass pointers to these variables to the function, like so:

void swap( int *a, int *b ) { int tmp = *a; *a = *b; *b = tmp; return; }
int x = 0, y = 1;
printf( "before swap: x = %d, y = %d\n", x, y );
swap( &x, &y );
printf( " after swap: x = %d, y = %d\n", x, y );

Instead of swapping the values of a and b, we swap the values of what a and b point to; the expressions *a and *b refer to the same objects in memory as x and y.

This is why you must pass a pointer to i in the scanf call (the scanf conversion specifier %d expects the corresponding argument to have type int *); you would not be able to update the value of i otherwise.

I haven't been too impressed with "Learn C The Hard Way"; then again, almost all C references have some fatal flaws. Kernighan and Ritchie's The C Programming Language, while pretty long in the tooth (it doesn't cover anything introduced in the last two standard revisions), is still probably the best overall introduction to the language. I've also heard good things about King's C Programming: A Modern Approach. My go-to desktop reference is Harbison & Steele's C: A Reference Manual, although it's exactly what it says it is - a reference manual, and as such not that big on explaining basic concepts.

I would like to know what I should use to compile in C. I am brand new to programing in general and would greatly appreciate a comprehensive explanation of this process. I am on Windows Vista.

I heard about something called "djgpp" that is free and effective for windows.

Depends on which platform, but on Linux, Mac OS X and similar (including Cygwin), gcc is most common.

Say I have a script named myapp.c:

#import <stdio.h>

int main(){
        return 0;

To compile it from the command line using gcc is very simple, just run:

gcc myapp.c

..that outputs the binary as "a.out" (the default filename). To run the compiled app, just do..

#which outputs: Hi!

Or put it somewhere within your $PATH (for example, /usr/bin or ~/bin/) and run a.out

You can specify the output filename with the -o flag:

gcc myapp.c -o myapp
# output: Hi!

As for more complete guides, "Learn C for Cocoa" is a good, quick guide on the C language, and covers compiling. If you're interested in learning ObjC, the next part of the guide is also great.

On Windows, I would recommend looking into Visual Studio, specifically the Express editions (which are free).

There's no "Visual C", but the Visual C++ edition will compile C code (since C++ is an extension of C). There's also an option to "Compile as C code" somewhere in the build options.

Finally, The C Programming Language book covers, well, everything.

For the answer to this question and many others you may have as you start out, try this website which has beginner tutorials. Here's the page on compilers and getting set up. An excerpt on what compilers you can use:


  • Code::Blocks and MINGW
  • Borland
  • Dev-C++ and Digital Mars

Windows Only

  • Microsoft Visual C++
  • nix
  • g++ is a C++ compiler that comes with most *nix distributions.
  • gcc is a C compiler that comes with most *nix distributions.

Macintosh - XCode


Personally, I'd also recommend you strongly to read The C Programming Language by Kernighan and Ritchie. It will really help you understand both core principles of programming as well as C-specific details.

Lately all modern programming languages have a definitive web site to support, distribute, learn the programming language, as well as community forums, e-mail lists and so on. Java has, python has, etc.

However C/C++ does not seem to have such a site. Which site do you use, say in a document, to link for C or C++ programming language? Wikipedia entries don't count, although they might be perfect fit.

Founder's web sites? Or any other ideas?

These languages have been around longer than the Internet as we know it. A lot of the introductory texts are in dead-tree format. Most of the online stuff is reference material, but there are newsgroups and such (I don't follow any of them).

The C Programming Language

Any reference for the C or C++ standard libraries.

C++ Specific:

C++ FAQ Lite


My goals are focused on software application development, and maybe web application development, but most likely desktop applications. I'm embarking on a path to becoming more familiar with C/C++, but should I go much lower than that, into assembly? Or would I not have a benefit for my long-term goals?


I learnt PDP assembler when I did my Elect. Eng. degree in the late '70's. The last dialect of assembler that I really used had four different modes of memory addressing. Last dialect I ooked at had 17 modes!

Not sure what learning assembler really gives you nowadays. Back then it was an essential part of a CS stream in my elect. eng. degree.

As to learning C++ I'd just sit down and work through "Accelerated C++" which approaches C++ in its own right and not as "C with other bits".

As to C, I'd just work through the latest version of "C Programming Lanuage" (a.k.a.) K'n'R

Hope this helps.

cheers, Rob

Now if you'd asked about nano-progrmming... (-:

Ruby modulo rules with negative numbers are unclear. In IRB:

-7 % 3 == 2  

Should be 1! Why?

When one of the operands to % is negative, there’s no clear best answer for what result to return. Every programming language has its own rules. The Wikipedia page for Modulo operation has a giant table of how each programming language has decided to handle this, and there’s no clear consensus:

$ # Modulus sign is:
$ curl '' \
    | egrep -o 'Divisor|Dividend|Always positive|Closest to zero|Not defined|Implementation defined' \
    | sort | uniq -c | sort -nr

  67 Dividend
  42 Divisor
   7 Always positive
   4 Closest to zero
   2 Not defined
   2 Implementation defined

Some choose the sign of the left-hand operand, and some the right-hand operand. Others don’t specify. For example, The C Programming Language says:

the sign of the result for % [is] machine-dependent for negative operands

Instead of making a particular choice for how to handle this, C just returns whatever the particular hardware or compiler being used have chosen to implement! This seems to have been standardized in more recent versions of the C programming language standards.

If you want to get a particular version in Ruby, there are two different methods you could call, modulo aka %, and remainder, with different behaviour on negative numbers:

$ irb
irb(main):001:0> -7.modulo(3)
=> 2
irb(main):002:0> -7.remainder(3)
=> -1

In other languages that don’t have built-in methods for this, you may end up using % twice to get the desired sign.

Possible Duplicate:
The Definitive C Book Guide and List
Good open source code for C++

I started learning C++ over 2 years ago. Since then, i went back and learned C, among other programming languages, but C is my favorite. While looking at open-source projects recently, i quickly realized that my code is ugly, barely readable, and the opposite of extendable. I want this to change. Any references/links to any books, websites, or other resources that would better help me program in C more professionally would be greatly appreciated.


Hmm you say you know C but it's not bad to mention the definite guide which is Dennis Ritchie's own book The C Programming Language. Another book I have heard good things about is Programming in C by Stephen G Kochan, even though I have not read it myself.

But in my opinion the best way to actually learn to write optimal code is to try it. Make many projects, and fail at doing so. Then be forced to search the net for what made you fail or what a bug might be, realize that you wasted 2 days over a bug that could have been avoided if you had followed some programming standards and then learn from that experience

:::::Binary Tree insertion::::

#include "stdafx.h"
#include <iostream>

using namespace std;

struct TreeNode {
  int value;
  TreeNode* left;
  TreeNode* right;

struct TreeType {
  TreeNode* root;

  void insert(TreeNode* tree, int item);

  void insertItem(int value) {
    insert(root, value);

void TreeType::insert(TreeNode* tree, int number) {
  if (tree == NULL) {
    tree = new TreeNode;
    tree->left = NULL;
    tree->right = NULL;
    tree->value = number;
    cout << "DONE";
  } else if (number < tree->value) {
    insert(tree->left, number);
  } else {
    insert(tree->right, number);

int main() {
  TreeType* MyTree = new TreeType;

  return 0;

I am currently learning Data structures in C++ and this is the code that make insertion in binary trees.

After it is compiled, everything looks fine, however when i try to execute this program, it crashed.

Can anybody tell me where I am wrong?

In your tree constructor, you need to initialize the root pointer to NULL. It's not guaranteed to be initialized as NULL.

When you compile in linux, you can use gdb to show where the source of the segfault is coming from.

Some other notes:

  1. You should assign the value back to root after you've allocated the new node. You're not doing that because you're missing one of the fundamentals of c++. That is, it's based on c. And the thing about c is that is strictly a "by-value" function/method calling paradigm. So all parameters in a function call are by value. When you pass in the memory address for root, you're actually copying the value of the pointer. Then, you're only updating the local value. You need to assign it back to root. If you'd like to learn that concept front to back, I highly recommend watching Jerry Cain's Programming Paradigms course at Stanford.
  2. In your main function, you should try to keep the symbol names as lower_case instead of CamelCase. This helps differentiate variables from types (types should stay CamelCase).
  3. In your TreeType::insert method, you should call the variable tree_node instead of tree. Doing so helps reflect the correct type and avoids confusion.
  4. Whenever possible, try you use the this->root and this->insert notation. Not only will it correctly resolve if you accidentally create a locally scoped root variable, but it's also clearer to the reader where the data or method is defined. Great coding is about communication. It may only take 100-500ms less for the reader to understand where the symbol points to; however, the tiny savings that you can accumulate in avoiding ambiguities add up into a much clearer piece of software. Your future self (and your colleagues) will thank you. See

Lastly, I can overstate enough how important learning from the source is. If you're learning c or c++ for the first time, read and It will save you hours, upon hours, upon hours. After having learned from the source, programming is also A LOT more enjoyable because you understand a good portion of the concepts. And, the truth is, things are more fun when you have a decent level of competence in them.

Here's what I'm trying to do:

myValueType function1(myParam){}

myValueType function2(myParam){}

myArray[CONSTANT_STATE1] = &function1;
myArray[CONSTANT_STATE2] = &function2;

myValue = (*myArray[CONSTANT_STATE1])(myParam);

When I compile, it throws an error that I've redeclared function1.

What's the best way to do this?

As per this SO answer from user Vijay Mathew:

Section 6.6 of The C Programming Language presents a simple dictionary (hashtable) data structure. I don't think a useful dictionary implementation could get any simpler than this. For your convenience, I reproduce the code here.

struct nlist { /* table entry: */
    struct nlist *next; /* next entry in chain */
    char *name; /* defined name */
    char *defn; /* replacement text */

#define HASHSIZE 101
static struct nlist *hashtab[HASHSIZE]; /* pointer table */

/* hash: form hash value for string s */
unsigned hash(char *s)
    unsigned hashval;
    for (hashval = 0; *s != ’\0’; s++)
      hashval = *s + 31 * hashval;
    return hashval % HASHSIZE;

/* lookup: look for s in hashtab */
struct nlist *lookup(char *s)
    struct nlist *np;
    for (np = hashtab[hash(s)]; np != NULL; np = np->next)
        if (strcmp(s, np->name) == 0)
          return np; /* found */
    return NULL; /* not found */

char *strdup(char *);
/* install: put (name, defn) in hashtab */
struct nlist *install(char *name, char *defn)
    struct nlist *np;
    unsigned hashval;
    if ((np = lookup(name)) == NULL) { /* not found */
        np = (struct nlist *) malloc(sizeof(*np));
        if (np == NULL || (np->name = strdup(name)) == NULL)
          return NULL;
        hashval = hash(name);
        np->next = hashtab[hashval];
        hashtab[hashval] = np;
    } else /* already there */
        free((void *) np->defn); /*free previous defn */
    if ((np->defn = strdup(defn)) == NULL)
       return NULL;
    return np;

char *strdup(char *s) /* make a duplicate of s */
    char *p;
    p = (char *) malloc(strlen(s)+1); /* +1 for ’\0’ */
    if (p != NULL)
       strcpy(p, s);
    return p;

Note that if the hashes of two strings collide, it may lead to an O(n) lookup time. You can reduce the likely hood of collisions by increasing the value of HASHSIZE. For a complete discussion of the data structure, please consult the book.

I am currently reading this book: The C Programming Language - By Kernighan and Ritchie (second Edition) and one of the examples I am having trouble understanding how to check whether the input is digit or not. The example is on Page 22, explaining under the array chapter.

Below is the example.

#include <stdio.h>

 /* count digits, white space, others */

   int c, i, nwhite, nother;
   int ndigit[10];

   nwhite = nother = 0;

   for (i = 0; i < 10; ++i)
       ndigit[i] = 0;

   while ((c = getchar()) != EOF)
     if (c >= '0' && c <= '9')
     else if (c == ' ' || c == '\n' || c == '\t')

   printf("digits =");

   for (i = 0; i < 10; ++i)
      printf(" %d", ndigit[i]);

   printf(", white space = %d, other = %d\n",nwhite, nother);

For this example, what confused me is that the author mentioned that the line ++ndigit[c-'0'] checks whether the input character in c is a digit or not. However, I believe that only the if statement ( if (c>= '0' && c<= '9') ) is necessary, and it will check if c is digit or not. Plus, I do not understand why [c-'0'] will check the input(c) is digit or not while the input variable (c) is subtracted from the string-casting ('0').

Any suggestions/explanations would be really appreciated.

Thanks in advance :)

I am trying to code a trival interview question of reversing a string.

This is my code:

#include <string.h>

char* rev( char* str)
    int i,j,l;

    l = strlen(str);

    for(i=0,j=l-1; i<l/2 ; i++, j--)
        str[i] = (str[i] + str[j]);
        str[j] = str[i] - str[j];
        str[j] = str[i] - str[j];

    return str;

int main()
    char *str = " hello";
    printf("\nthe reverse is %s ...", rev(str));

    return 1;

Basically, this one gives a segmentation fault.

I have following questions:

  1. I get segmentation fault probably because, the characters add up to something not defined in ascii and hence I cannot store them back as characters, I am using [I wonder if it supports just ascii !!] . Is my understanding correct or there is something else to it.

  2. How do I correct the problem , for the same platform [I mean swapping in place for]

  3. Here I have to use an additional integer l to calculate length. So to save a single char space by swapping in place .. I am using an extra int !!! .. just to impress the inteviewer :) ... Is this approach eve worth it !!!

  4. This one is for those who are interested in writing unit tests/API tests . I want to have a robust implementation so what can be possible test cases. I assume that if interviewer asks such a simple question .. he definitely wants some very roboust implementation and test cases. Few that I thought off:

    • passing empty strings passing integer

    • strings passing integer array instead of char array.

    • very long string ,

    • single char string string of special chars.

Any advise/suggestions would be helpful.

Page 62 of Kernighan & Ritchie's The C Programming Language shows an algorithm for in-place string reversal with a temporary variable.

Similar to this:

char* rev_string(char* const str)
  int i, j;
  char tmp;
  for(i = 0, j = strlen(str)-1; i < j; i++; j--)
    tmp = str[i];
    str[i] = str[j];
    str[j] = tmp;
  return str;

This algorithm is easier to understand than the one without a temporary variable, imho.

As for item #3 in your list of questions:

As an interviewer, I would want to see simple, clear, and well structured code. That's impressive. Trickery will not impress me. Especially when its comes to premature optimization. BTW, my solution reverses the string in place with one additional char instead of an int. Impressive? :)

And item #4:

One other test case would be an unterminated string. Is your function robust enough to handle this case? Your function will only be as robust as the least robust part of it. Passing an unterminated string into my solution causes a Segmentation Fault, due to strlen reporting an incorrect string length. Not very robust.

The important point about robustness is, your code might be robust but you have to make sure all other external functions you use are, too!

I have recently started working on my master thesis in C that I haven't used in quite a long time. Being used to Java, I'm now facing all kinds of problems all the time. I hope someone can help me with the following one, since I've been struggling with it for the past two days.

So I have a really basic model of a database: tables, tuples, attributes and I'm trying to load some data into this structure. Following are the definitions:

typedef struct attribute
    int type;
    char * name;
    void * value;
} attribute;

typedef struct tuple
    int tuple_id;
    int attribute_count;
    attribute * attributes;
} tuple;

typedef struct table
    char * name;
    int row_count;
    tuple * tuples;
} table;

Data is coming from a file with inserts (generated for the Wisconsin benchmark), which I'm parsing. I have only integer or string values. A sample row would look like:

insert into table values (9205, 541, 1, 1, 5, 5, 5, 5, 0, 1, 9205, 10, 11, 'HHHHHHH', 'HHHHHHH', 'HHHHHHH');

I've "managed" to load and parse the data and also to assign it. However, the assignment bit is buggy, since all values point to the same memory location, i.e. all rows look identical after I've loaded the data. Here is what I do:

char value[10]; // assuming no value is longer than 10 chars
int i, j, k;

table * data = (table*) malloc(sizeof(data));
data->name = "table";
data->row_count = number_of_lines;
data->tuples = (tuple*) malloc(number_of_lines*sizeof(tuple));

tuple* current_tuple;

for(i=0; i<number_of_lines; i++)
    current_tuple = &data->tuples[i];
    current_tuple->tuple_id = i;
    current_tuple->attribute_count = 16; // static in our system
    current_tuple->attributes = (attribute*) malloc(16*sizeof(attribute));

    for(k = 0; k < 16; k++)
        current_tuple->attributes[k].name = attribute_names[k];

        // for int values:
        current_tuple->attributes[k].type = DB_ATT_TYPE_INT;
        // write data into value-field
        int v = atoi(value);
        current_tuple->attributes[k].value = &v;

        // for string values:
        current_tuple->attributes[k].type = DB_ATT_TYPE_STRING;
        current_tuple->attributes[k].value = value;

    // ...

While I am perfectly aware, why this is not working, I can't figure out how to get it working. I've tried following things, none of which worked:

 memcpy(current_tuple->attributes[k].value, &v, sizeof(int));

This results in a bad access error. Same for the following code (since I'm not quite sure which one would be the correct usage):

 memcpy(current_tuple->attributes[k].value, &v, 1);

Not even sure if memcpy is what I need here...

Also I've tried allocating memory, by doing something like:

 current_tuple->attributes[k].value = (int *) malloc(sizeof(int));

only to get "malloc: *** error for object 0x100108e98: incorrect checksum for freed object - object was probably modified after being freed." As far as I understand this error, memory has already been allocated for this object, but I don't see where this happened. Doesn't the malloc(sizeof(attribute)) only allocate the memory needed to store an integer and two pointers (i.e. not the memory those pointers point to)?

Any help would be greatly appreciated!

Regards, Vassil

So, you have several things going on here. First, don't cast the return value of malloc in the C programming language. Next, this is going to cause troubles:

int v = atoi(value);
current_tuple->attributes[k].value = &v;

You are having value point to memory allocated on the stack. That's bad if you access it after that current "v" has gone out of scope.

Also, you are not using any branching condition to determine if the value should be string or int. Therefore, you will end up with memory leaks, assuming you assigned things properly as mentioned before. I suspect this is partly because it is just an example.

Check the return value of malloc. You can create a wrapper function to do this for you. Also, you may want to do some better logging.

Essentially, you need to become more familiar with how pointers work in C and the difference between allocating on the heap and allocating on the stack. Stack or automatic variables go out of scope. When you malloc it stays around forever until you get rid of it. Don't ever set a pointer equal to the memory location of something allocated on the stack unless you really mean to do that (again, your example with "v", that memory address will be invalid as soon as that particular iteration of the loop is finished, the worst case here is that it works when you test it and you don't notice the error.

Additionally, "//" is not ANSI-C89 style comment. Use "/" and "/"

I made a couple changes; I can't guarantee it will work now as I haven't tested it obviously. However, I recommend reading the C Programming Language

char value[10]; /* assuming no value is longer than 10 chars */
int i, j, k;

table * data = malloc(sizeof(table));
         exit(1); /* error */

data->name = "table";
data->row_count = number_of_lines;
data->tuples = malloc(number_of_lines*sizeof(tuple));
         exit(1); /* error */

tuple* current_tuple;

for(i=0; i<number_of_lines; i++)
    current_tuple = &data->tuples[i];
    current_tuple->tuple_id = i;
    current_tuple->attribute_count = 16; /* static in our system */
    current_tuple->attributes = malloc(16*sizeof(attribute));

    for(k = 0; k < 16; k++)
        current_tuple->attributes[k].name = attribute_names[k];

                        if(k % 2)
               /* for int values:*/
               current_tuple->attributes[k].type = DB_ATT_TYPE_INT;
               /* write data into value-field */
                               current_tuple->attributes[k].value = malloc(sizeof(int));
                                    exit(1); /* error */
               *current_tuple->attributes[k].value = atoi(value);

               /* for string values: */
               current_tuple->attributes[k].type = DB_ATT_TYPE_STRING;
                               current_tuple->attributes[k].value = malloc(strlen(value) +1);
                                    exit(1); /* error */
               strcpy(current_tuple->attributes[k].value, value);


I learning these concepts, please help me why the following code is throwing a segmentation fault. My intention in this code is to print capital letter D and move to next address. Please explain me. thank u.

    char *ptr="C programming";
    printf(" %c \n",++*ptr);    

Reason for your error

You are trying to modify a string literal, which is a non-modifiable object. That's why you get a segmentation fault.

Even if you simply call ptr[0]++, it will be a segmentation fault.


One solution is to change the declaration to:

char ptr[] = "C programming"

Then you can modify the char array.

They look similar? Yes, the string literal is still non-modifiable, but you have declared an array with its own space, which will be initialized by the string literal, and the array is stored in the stack, and thus modifiable.


Here is a full code example:

#include <stdio.h>

int test() {
    char str[]="C programming";
    char *ptr = str;

    while(*ptr != '\0') {
        // print original char,
        printf("%c \n", *(ptr++));

        // print original char plus 1, but don't change array,
        // printf("%c \n", (*(ptr++))+1);

        // modify char of array to plus 1 first, then print,
        // printf("%c \n", ++(*(ptr++)));

    return 0;

int main(int argc, char * argv[]) {
    return 0;

Tip: you should only enable one of the printf() lines at the same time, due to ++ operator.

More tips

Note that we declared a ptr and a str, because we can't use ++ operation on an array (you can't change the address of an array), thus ++str will get a compile error, while ++ptr won't.

@Update - About memory

(To answer your comment)

  • A string literal is usually stored in a read-only area of a process; refer to C string literals: Where do they go?
  • A char array, if declared inside a method, then it's allocated on the stack, thus you can modify it; when you initialize a char array from a string literal, there are actually 2 copies of the same value: 1 is read-only; 1 is modifiable; the char array is initialized from the read-only copy.
  • A char pointer it stores a single address; the pointer itself is allocated on stack in this case, and you can modify it.

You might also want to know more about pointer or address or array or Linux process memory layout_ or data sections of a C program; try searching on Google, or refer to books like The C Programming Language, 2nd Edn and The Linux Programming Interface — though this is a question about C rather than Linux. There's also The Definitive C Book Guide and List on Stack Overflow.

I needed a function to return a string. I used the following code to declare the function:

const char* serv_con(char app_data[50])
    char send_data[1024],recv_data[1024];
    //i am avoiding code segments irrelevant to the issue.
    return recv_data;

and then called the function in the main like this:

int main()
    char ser_data[50], app_data[50];
    ser_data[0] = '\0';
    app_data[0] = '\0';
    //avoiding code segments irrelevant to the issue.
    app_data = serv_con(ser_data); //function call

On compiling it gives the error:

connect.c:109: error: incompatible types when assigning to type ‘char[50]’ from type ‘const char *’

Then i replaced the const char in the declaration with std::string. The declaration now is as follows:

std::string serv_con(char app_data[50])
    char send_data[1024],recv_data[1024];
    //avoiding code segments irrelevant to the issue.
    return recv_data;

And called it in the same way as mentioned above. But still it gives the following error on compiling:

connect.c:13: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘:’ token

Please tell me how I can give a string as a return type from a function. The platform I work on is linux. Thanks in advance.

From your question I can be pretty sure that you are a beginner. Please go through a good text book i.e The C Programming Language.

Along with the error you must be getting this.
warning: function returns address of local variable.

Look at the warnings always. The question is already answered by Greg.

I've been thinking of making a desktop program but I have no experience in that. I've been programming in PHP, ASP and JavaScript before. Java seems to be nice since you can run it on all OS. But what I really want is result, I do not really care what language makes me a good programmer (I'll take that later in college :P). I've tried both C# and Python before but it was only console applications.

So, what programming language do you recommend to me?

Go through K&R C. Learn C and you should have a great foundation for learning other languages.

My structure looks as follows:

typedef struct {
      unsigned long attr;
      char fileName[128];
} entity;

Then I try to assign some values but get an error message...

int attribute = 100;
char* fileNameDir = "blabla....etc";

entity* aEntity;

aEntity->attr = attributes;
aEntity->fileName = fileNameDir;

Compiler tells me:

Error: #137: expression must be a modifiable lvalue aEntity->fileName = fileNameDir;

Why cant I assign here this character to the one in the structure?


  • You're treating a char[] (and a char*, FTM) as if it was a string. Which is is not. You can't assign to an array, you'll have to copy the values. Also, the length of 128 for file names seems arbitrary and might be a potential source for buffer overflows. What's wrong with using std::string? That gets your rid of all these problems.
  • You're defining a pointer to some entity, don't initialize it, and then use it as if at the random address it points to was a valid entity object.
  • There's no need to typedef a struct in C++, as, unlike to C, in C++ struct names live in the same name space as other names.

If you absolutely must use the struct as it is defined in your question (it is pre-defined), then look at the other answers and get yourself "The C Programming Language". Otherwise, you might want to use this code:

struct entity {
  unsigned long attr;
  std::string fileName;

entity aEntity;
aEntity.attr = 100;
aEntity.filename = "blabla....etc";

This was an job placement interview I faced. They asked whether we can realloc Array, I told yes. Then They asked - then why we need pointers as most of the people give reason that it wastes memory space. I could not able to give satisfactory answer. If any body can give any satisfactory answer, I'll be obliged. Please mention any situation where the above statement can contradict.

Thank you.

You can only reallocate an array that was allocated dynamically. If it was allocated statically, it cannot be reallocated [safely].*

Pointers hold addresses of data in memory. They can be allocated, deallocated, and reallocated dynamically using the new/delete operators in C++ and malloc/free in C.

I would strongly suggest that you read The C Programming Language by Kernighan and Ritchie and a solid C++ text like C++ From the Ground Up by Herbert Schildt.

Using dynamic memory, pointers, offsets, etc are all fundamental to using these two languages. Not knowing how they work, and why they exist will be a likely reason for potential employers to turn you down.

*the compiler shouldn't let you reallocate anything that's been allocated statically, but if it does, the behavior is undefined

Where can I find a C programming reference that will list the declaration of built-in functions?

Grab the K&R book, if you don't already have it.

Also, this page looks like it might be a good start for you.

Where to read up on (the best-practice in) source code formatting, for individual languages i.e. what are the conventions for naming variables etc., for indentation and where to place braces, how and where to include comments, etc.

For example for C Kernighan and Ritchie's book The C Programming Language and Linus Torvalds' Linux kernel coding style guide or Google's C++ Style Guide and for Perl at least perlstyle - Perl style guide.

Edit: Perhaps I should have asked "How to get a good start with coding styles".

I wouldn't give too much on such style-guides. They are a good start, but in the end you or your team will develop own coding-styles.

EDIT: Rob Kam made a comment, that he want to find out more about these 'starting-conventions'.

That's a good point. But mostly you will join existing projects, open-source-projects or commercial, and the people working on it already have a code-convention. In a company probably exists already a code convention. If you start a new project, start with the conventions of another project you did before.

If you really start a new project with a new language you didn't used before ... then you might start with conventions of another language that is somehow similar (i.e. for a new oo-language you can use conventions from Java or Smalltalk) and adjust your conventions as you gain experience for the new language. As I started programming in Java I used my Pascal-coding-conventions. Some of the pascal-conventions didn't work very good for Java, but with the time I dropped some old conventions and developed new.

S.Lott had the idea to look into an open-source-project written in the language of your choice. That's a good idea to get some suggestions about good conventions. Srikanth had the good idea to ask for good conventions here at Stackoverflow. A very good idea, because with the time Stackoverflow will become a good reference for coding-conventions this way.

I would really recommend to read uncle bob's Clean Code if you are concerned about code style issues.

Possible Duplicate: What is the difference between const int*, const int * const, and int const *?

What is the difference between the following?

char const *p;
const char  *p;
char *const p;

And is there a good site where I can relearn C and C++? It seems that I forgot it and job interviews are doing me an hard time...

  1. Buy a copy of Kernighan & Ritchie (K&R) and work through it.
  2. Do the exercises in K&R and understand the solutions provided in The C Answer Book.
  3. Buy a copy of Accelerated C++ and work through it, because it treats C++ as its own language and not just C with "bits bolted on".
  4. Buy a copy of Effective C++, don't violate the items and read each one to understand why you shouldn't violate them.

As an added bonus, read Effective STL to use the STL properly.

Possible Duplicate:
How to understand complicated function declarations?
Spiral rule and ‘declaration follows usage’ for parsing C expressions

There is a section with the same title, "Complicated Declarations", in K&R's The C Programming Language book as you might have already read. I am just reading the book and trying to better myself in C language. After reading the section mentioned, I think I couldn't get the logic behind the syntax of C declaration statements. 1, 2, 3 and 4 are from that section 5 and 6 are from other pages.

  1. int (*daytab)[13] daytab: pointer to array[13] of int

  2. void (*comp)() comp: pointer to function returning void

  3. char (*(*x())[])() x: function returning pointer to array[] of pointer to function returning char

  4. char (*(*x[3])())[5] x: array[3] of pointer to function returning pointer to array[5] of char

  5. typedef int (*PFI)(char *, char *) creates the type PFI, for ``pointer to function (of two char * arguments) returning int. How does the syntax works here?

Finally, my questions are:

  • Can you explain your ways of thinking and reading complicated declarations possibly by using examples above?
  • Are the things like 1,3,4 practically usable and needed? If so, can you write some code examples?

From this question I learned that you indeed should not export a local variable's address and use it outside the function in which it was declared.

However, it seems to me that K&R are breaking this rule in the program shown below taken from their book, p. 108.

I'm looking at the line lineptr[nlines++] = p; inside the function readlines. Why is it here OK to "export" p and use it later outside readlines?

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

#define MAXLINES 5000

char *lineptr[MAXLINES];

int readlines(char *lineptr[], int nlines);
void writelines(char *lineptr[], int nlines);

void qsort(char *lineptr[], int left, int right);

int main(int argc, char *argv[])
     int nlines;

     if((nlines = readlines(lineptr, MAXLINES)) >= 0) {
          qsort(lineptr, 0, nlines-1);
          writelines(lineptr, nlines);
          return 0;
     else {
          printf("error: input too big to sort\n");
          return 1;

#define MAXLEN 1000
int getline(char *, int);
char *alloc(int);

int readlines(char *lineptr[], int maxlines)
    int len, nlines;
    char *p, line[MAXLEN];

    nlines = 0;
    while((len = getline(line, MAXLEN)) > 0)
       if(nlines >= maxlines || (p = alloc(len)) == NULL)
          return -1;
       else {
            line[len-1] = '\0';
            strcpy(p, line);
            lineptr[nlines++] = p;
    return nlines;

void writelines(char *lineptr[], int nlines)
     while(nlines -- > 0)
         printf("%s\n", *lineptr++);

int getline(char s[], int lim)
  int c, i;

  for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; i++)
    s[i] = c;                                                         
  if (c == '\n') {
    s[i++] = c;   
  s[i] = '\0';
  return i;

#define ALLOCSIZE 10000

static char allocbuf[ALLOCSIZE];
static char *allocp = allocbuf;

char *alloc(int n)
     if(allocbuf + ALLOCSIZE - allocp >= n) {
          allocp +=n;
          return allocp - n;
          return 0;

void swap(char *v[], int i, int j)
     char *temp;

     temp = v[i];
     v[i] = v[j];
     v[j] = temp;

void qsort(char *v[], int left, int right) {

    int i, last;

    if(left >= right) 

    swap(v, left, (left+right)/2);
    last = left;

    for(i = left + 1; i <= right; i++)
      if(strcmp(v[i], v[left]) < 0)
         swap(v, ++last, i);

    swap(v, left, last);
    qsort(v, left, last-1);
    qsort(v, last+1, right);


lineptr[nlines++] = p;

the value of p is stored, not its address. The address is &p. Of course, the value of p happens to be an address, since p is a pointer, and the value of a pointer represents an address. But that has no consequence here. The rule is still being followed; no address of any local variable has been stored anywhere outside the function, and the value of p is not the address of a local variable.

If you follow the call chain you can determine that the value of p can be either 0, or be an address somewhere inside allocbuf. And allocbuf is not a local variable. It's a static variable at file scope.

Given a pointer to structure, can I write a #define that would access a member of the structure?

struct s_block {
 size_t size;
 struct s_block *ptr;

#define SIZER(ptr) // will access size member ???? 
#define SIZER(ptr) (ptr)->size

Do note though that you must pass in a pointer to an s_block for this to work.

Finally, this should be in any reference manual covering the C programming language. I suggest you pick one up. K&R is very good, even today.

I am reading PrenticeHall. The C Programming Language - 2nd Ed.Kernighan,Ritchie.

In this book(pg-20) an example of a program is given which is supposed to print the number of characters that user types in the console window, and here is its code .

#include <stdio.h>

    double nc;
    for (nc = 0; getchar() != EOF; ++nc)

    printf("%.0f\n", nc);

But when I run this , and type something in the console, it wont print anything at all, the cursor would keep on blinking . and this is exactly the way code is written in that book.

I have tried it another way also, but this also didn't work out, same result as that previous code.

#include <stdio.h>

    long nc;
    nc = 0;
    while (getchar() != EOF)

    printf("%ld\n", nc);

any ideas to how to make this thing work ?

P.S. I am using windows OS. (still)

The reason is that the code tries to read all the input until the end of file. If this program was reading from a file, it would know when it ended, but since it's reading from console, you have to explicitly tell it that the input is over. On Linux you do this by pressing ^D (Ctrl+D), on Windows ^Z (Ctrl+Z).

Note that it has to be done at the start of a new line, i.e. after pressing Enter, you press ^D (^Z on Win).

I am reading PrenticeHall. The Ansi C Programming Language - 2nd Ed.Kernighan,Ritchie.

That's a very good book you're reading. It's that good, I guess, it contains the answer to your question.

I am writing a program which takes user input to determine pair of numbers and swaps values of all the pairs entered by the user.

For example:

User wants to enter 3 pairs, then he would enter 3 followed by pairs:

3 1 2 3 4 5 6


2 1 4 3 6 5

My program is giving proper output but instead of taking all pairs at once, it takes them one by one and gives the output. I have a vague idea that this can be resolved by using array but not sure how. Please help.

Here is my code:

#include <stdio.h>
int main()
    int x, y, p, i;
   //int a [100], b[100];
    printf ("How many pairs?\n");
    scanf ("%d", &p);
    for(i=1; i<=p; i++)
       printf ("Enter two values:\n");
       scanf("%d %d",&x,&y);

       x = x + y;  
       y = x - y;  
       x = x - y;

      printf("After Swapping: x = %d, y = %d\n", x, y);

     return 0;

Currently the output looks like:

How many pairs? 2

Enter two values: 2 3

After swapping x= 3 and y=2

Enter two values: 4 5

After swapping x= 5 and y=4. I want it to take all 4 values together and display output.

I'm assuming you're working on C so I've only used C headers. One way to do this is to first find out how many pairs there are, dynamically allocate space as is applicable, fill the array with the input integers, swap them, and then print them.

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

int main()
    printf("Enter numbers: ");

    /* Get the number of pairs. */
    int prs;

    /* Create a dynamic array. */
    int *A = (int*) malloc(prs*sizeof(int));

    /* Read the integers into the array. */
    int i=0;

    /* Swap. */
    int j=0;
        int tmp = A[j];
        A[j] = A[j+1];
        A[j+1] = tmp;

    /* Print. */
    for(i=0;i!=j;printf("%i ",A[i++]));

Cheers ! If you're interested in really getting good, try this book.

I have just started reading through The C Programming Language and I am having trouble understanding one part. Here is an excerpt from page 24:





          ++ndigit[c-'0']; //THIS IS THE LINE I AM WONDERING ABOUT
      else if(c==''||c=='\n'||c=='\t')


The output of this program run on itself is


The declaration


declares ndigit to be an array of 10 integers. Array subscripts always start at zero in C, so the elements are

ndigit[0], ndigit[ 1], ..., ndigit[9]

This is reflected in the for loops that initialize and print the array. A subscript can be any integer expression, which includes integer variables like i,and integer constants. This particular program relies on the properties of the character representation of the digits. For example, the test


determines whether the character in c is a digit. If it is, the numeric value of that digit is


This works only if '0', '1', ..., '9' have consecutive increasing values. Fortunately, this is true for all character sets. By definition, chars are just small integers, so char variables and constants are identical to ints in arithmetic expressions. This is natural and convenient; for example


is an integer expression with a value between 0 and 9 corresponding to the character '0' to '9' stored in c, and thus a valid subscript for the array ndigit.

The part I am having trouble understanding is why the -'0' part is necessary in the expression c-'0'. If a character is a small integer as the author says, and the digit characters correspond to their numeric values, then what is -'0' doing?

Digit characters don't correspond to their numeric values. They correspond to their encoding values (in this case, ASCII).

IIRC, ascii '0' is the value 48. And, luckily for this example and most character sets, the values of '0' through '9' are stored in order in the character set.

So, subtracting the ASCII value for '0' from any ASCII digit returns its "true" value of 0-9.

I have three c files one.c, two.c and three.c on Linux in same folder I need to first run one.c file and then as soon as it completes running it should automatically run two.c file. After two.c file completes running it should automatically run three.c and so on...

All the files will be compiled.

Thanks in advance !!! !! !

Looks like you could use a beginner's reference, such as this one.

This book doesn't hurt either.

Both of them are small books, but it's best to go to the source when starting out.

Best of luck!

I'm a web coder: I currently enjoy AS3 and deal with PHP. I own a Nintendo DS and want to give C a go.

From a higher level, what basic things/creature comforts are going to go missing? I can't find [for... in] loops, so I assume they aren't there. It looks like I'm going to have to declare things religiously, and I assume I have no objects (which I dealt with in PHP a while ago).

Hash tables? Funny data types?

C is the next level above straight assembler and allows you to operate close to the metal. This gives power to do amazing stuff but also to easily shoot yourself in the foot!

One such example is direct memory access and the perils and wonder of pointer arithmetic. Pointers are very powerful, fast, and handy however require careful management. See this SO question for an example.

Also as mentioned by the other answerers you will have to do your own memory management. Again powerful and painful.

I would recommend studying up a good textbook and find some quality example code. The key thing is to learn the patterns that make all this stuff hang together correctly and elegantly (well, as much as possible). A good debugger will also really help and get familiar with the standard C libraries too.

You may notice your applications crashing at the drop of a hat initially but perservere as C is definitely worth at least dabbling in. You will understand some of the amazing abstractions higher level languages provide and what is really going on under the hood.

I want to learn computer vision using specifically C or C++. I am a pretty strong coder, but I'm used to high level languages like python, etc.

To this end, I need to first learn the language. I don't want to jump right into image processing with a language I don't understand. I also learn best with practical examples.

  1. what resources can you recommend? good tutorials or practice projects?
  2. Best IDE on mac os x for this? I'm thinking Eclipse.
  3. focus on C or C++?

Thanks for your advice

There's one book to read for learning C: Kernighan and Ritchie's ANSI C. It has the added virtue of being thin but dense with information.

You can think of C++ as "a better C". I don't know what to recommend as the best text to learn it; it's been 15 years since I last wrote C++. Stroustrup developed it; try his books.

I don't know if it's THE language for computer vision. Understanding such a topic is far more than knowing a particular language. There's a lot to know: AI, mathematics, physics, etc.

string s="abcdefghijklmnopqrstuvwxyz"
char f[]=" " (s.substr(s.length()-10,9)).c_str() " ";

I want to get the last 9 characters of s and add " " to the beginning and the end of the substring, and store it as a char[]. I don't understand why this doesn't work even though char f[]=" " "a" " " does.

Is (s.substr(s.length()-10,9)).c_str() not a string literal?

@Xeo tells you how to solve your problem. Here's some complimentary background on how string literals are handled in the compilation process.

From section A.12 Preprocessing of The C Programming language:

Escape sequences in character constants and string literals (Pars. A.2.5.2, A.2.6) are replaced by their equivalents; then adjacent string literals are concatenated.

It's the Preprocessor, not the compiler, who's responsible for the concatenation. (You asked for a C++ answer. I expect that C++ treats string literals the same way as C). The preprocessor has only a limited knowledge of the C/C++ language; the (s.substr(s.length()-10,9)).c_str() part is not evaluated at the preprocessor stage.

This question is from Learn C the Hard Way by Zed Shaw. It's about pointers and arrays. We are given some code here:

#include <stdio.h>

int main(int argc, char *argv[])
  // create two arrays we care about
  int ages[] = {23, 43, 12, 89, 2};
  char *names[] = {
      "Alan", "Frank",
      "Mary", "John", "Lisa"

  // safely get the size of ages
  int count = sizeof(ages) / sizeof(int);
  int i = 0;

  // first way using indexing
  for(i = 0; i < count; i++) {
      printf("%s has %d years alive.\n",
              names[i], ages[i]);


  // setup the pointers to the start of the arrays
  int *cur_age = ages;
  char **cur_name = names;

  // second way using pointers
  for(i = 0; i < count; i++) {
      printf("%s is %d years old.\n",
            *(cur_name+i), *(cur_age+i));


  // third way, pointers are just arrays
  for(i = 0; i < count; i++) {
      printf("%s is %d years old again.\n",
              cur_name[i], cur_age[i]);


  // fourth way with pointers in a stupid complex way
  for(cur_name = names, cur_age = ages;
          (cur_age - ages) < count;
          cur_name++, cur_age++)
      printf("%s lived %d years so far.\n",
              *cur_name, *cur_age);

  return 0;

The directive is to "rewrite all the array usage in this program so that it's pointers." Does this mean to do something like?

int *ptr;
ptr = &ages[0]

Let me start off by saying something a little off topic:

  • I don't think this is a very good book. I think it confuses some topics to make them seem harder than they really are. For a better advanced C book, I would recommend Deep C Secrets by Peter van der Linden, and for a beginner's book, I'd recommend the original K & R

Anyway, it looks like you're looking at the extra credit exercises from this chapter.

  • Another aside- I don't think this is an especially sensible exercise for learning (another answer pointed out the question isn't formed to make sense), so this discussion is going to get a little complex. I would instead recommend the exercises from Chapter 5 of K & R.

First we need to understand that pointers are not the same as arrays. I've expanded on this in another answer here, and I'm going to borrow the same diagram from the C FAQ. Here's what's happening in memory when we declare an array or a pointer:

 char a[] = "hello";  // array

a: | h | e | l | l | o |\0 |

 char *p = "world"; // pointer

   +-----+     +---+---+---+---+---+---+
p: |  *======> | w | o | r | l | d |\0 |
   +-----+     +---+---+---+---+---+---+

So, in the code from the book, when we say:

int ages[] = {23, 43, 12, 89, 2};

We get:

ages: | 23 | 43 | 12 | 89 | 2 |

I'm going to use an illegal statement for the purpose of explanation - if we could have said:

int *ages = {23, 43, 12, 89, 2}; // The C grammar prohibits initialised array
                                 // declarations being assigned to pointers, 
                                 // but I'll get to that

It would have resulted in:

      +---+     +----+----+----+----+---+
ages: | *=====> | 23 | 43 | 12 | 89 | 2 |
      +---+     +----+----+----+----+---+

Both of these can be accessed the same way later on - the first element "23" can be accessed by ages[0], regardless of whether it's an array or a pointer. So far so good.

However, when we want to get the count we run in to problems. C doesn't know how big arrays are - it only knows how big (in bytes) the variables it knows about are. This means, with the array, you can work out the size by saying:

int count = sizeof(ages) / sizeof(int);

or, more safely:

int count = sizeof(ages) / sizeof(count[0]);

In the array case, this says:

int count = the number of bytes in (an array of 6 integers) / 
                 the number of bytes in (an integer)

which correctly gives the length of the array. However, for the pointer case, it will read:

int count = the number of bytes in (**a pointer**) /
                 the number of bytes in (an integer)

which is almost certainly not the same as the length of the array. Where pointers to arrays are used, we need to use another method to work out how long the array is. In C, it is normal to either:

  • Remember how many elements there were:

    int *ages = {23, 43, 12, 89, 2}; // Remember you can't actually
                                     // assign like this, see below
    int ages_length = 5;
    for (i = 0 ; i < args_length; i++) {
  • or, keep a sentinel value (that will never occur as an actual value in the array) to indicate the end of the array:

    int *ages = {23, 43, 12, 89, 2, -1}; // Remember you can't actually
                                         // assign like this, see below
    for (i = 0; ages[i] != -1; i++) {

    (this is how strings work, using the special NUL value '\0' to indicate the end of a string)

Now, remember that I said you can't actually write:

    int *ages = {23, 43, 12, 89, 2, -1}; // Illegal

This is because the compiler won't let you assign an implicit array to a pointer. If you REALLY want to, you can write:

    int *ages = (int *) (int []) {23, 43, 12, 89, 2, -1}; // Horrible style 

But don't, because it is extremely unpleasant to read. For the purposes of this exercise, I would probably write:

    int ages_array[] = {23, 43, 12, 89, 2, -1};
    int *ages_pointer = ages_array;

Note that the compiler is "decaying" the array name to a pointer to it's first element there - it's as if you had written:

    int ages_array[] = {23, 43, 12, 89, 2, -1};
    int *ages_pointer = &(ages_array[0]);

However - you can also dynamically allocate the arrays. For this example code, it will become quite wordy, but we can do it as a learning exercise. Instead of writing:

int ages[] = {23, 43, 12, 89, 2};

We could allocate the memory using malloc:

int *ages = malloc(sizeof(int) * 5); // create enough space for 5 integers
if (ages == NULL) { 
   /* we're out of memory, print an error and exit */ 
ages[0] = 23;
ages[1] = 43;
ages[2] = 12;
ages[3] = 89;
ages[4] = 2;

Note that we then need to free ages when we're done with the memory:


Note that there are a few ways to write the malloc call:

 int *ages = malloc(sizeof(int) * 5);

This is clearer to read for a beginner, but generally considered bad style because there are two places you need to change if you change the type of ages. Instead, you can write either of:

 int *ages = malloc(sizeof(ages[0]) * 5);
 int *ages = malloc(sizeof(*ages) * 5);

These statements are equivalent - which you choose is a matter of personal style. I prefer the first one.

One final thing - if we're changing the code over to use arrays, you might look at changing this:

int main(int argc, char *argv[]) {

But, you don't need to. The reason why is a little subtle. First, this declaration:

char *argv[]

says "there is an array of pointers-to-char called argv". However, the compiler treats arrays in function arguments as a pointer to the first element of the array, so if you write:

int main(int argc, char *argv[]) {

The compiler will actually see:

int main(int argc, char **argv)

This is also the reason that you can omit the length of the first dimension of a multidimensional array used as a function argument - the compiler won't see it.

Possible Duplicates:
C function syntax, parameter types declared after parameter list
What is useful about this C syntax?
Why are declarations put between func() and {}?

Hi guys,

I downloaded the glibc. I want to reuse some code part from this librairy, but there is somethings weird in this code. In fact, the parameters declaration are strange. The type of the parameters declared after que parantheses. I never saw that before. What is this kind of declaration? I not am able to compile it.

_ufc_doit_r(itr, __data, res)
     ufc_long itr, *res;
     struct crypt_data * __restrict __data;

This is called "K&R" style, from Kernighan and Ritchie, who wrote the book The C Programming Language. In the first edition of that book, the above was the only way to declare the types of parameters. I believe the second edition uses the standard style, with the types and names both within parentheses:

_ufc_doit_r(ufc_long itr,
            struct crypt_data * __restrict __data,
            ufc_long *res)

K&R style is a very old style of declaring parameters, but some people still use it so their code can compile on very old compilers.

A lot of other languages have good documentation for their language, but I see various implementations and would just like to see some documentation explaining things like those listed in the Title.

One great example I've used in the past (not the language itself, but the documentation) is from AS3:

Anything out there that I can use that is similar or just as good?

Since Objective C is an expansion of C, I suggest the C 'bible' from Kernichan and Ritchie.

Asking for a sanity check on this design choice.

I'm writing a heap sort in C by creating a heap data structure that can accept node types of string or numerical. (I'm creating my own private heap that I can sort)

The nodes in the heap are void*, which are dereferenced to perform the comparison operations. The Heap struct stores the sizeof each node in Heap.nodesize, or -1 if the node is a string.

When a node is inserted, memory is allocated for the void*. If the Heap.nodesize is -1, strlen(val) is passed to malloc, otherwise Heap.nodesize is passed to malloc.

When performing comparisons, if Heap.nodesize is -1 strcmp is used, otherwise boolean operators are used for the numerical.

When the heap is freed, I plan to loop through and free each void*. At this point will free know how many bytes to free for each node?

free don't need to know the number of bytes,just use it as 'Jonathon Reinhart' said.There is a simple implementation of malloc and free in chapter 8 in TCPL.Just read it,and you will know how free works without knowing the size of you dynamic allocated memory.Hope it works!

First I would like to thank everyone for everything they have ever done for me whether they knew it or not. I am a first time poster long time lurker.

I am starting a new class that is based around C and several of its variants. The problem is it assumes you have experience with at least C++, and I unfortunately have only taken a couple semesters of Java and Mips. I am struggling to learn C right now with no book or lesson plan going over it. I have survived this first month using Google. But my question today I just cannot seem to wrap my head around, and while I know it is elementary I would like some help understanding the working of the code in my assignment.

The professor has supplied us with the following code:

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

void encrypt(int offset, char *str) {

    int i,l;


    printf("\nUnencrypted str = \n%s\n", str);

        if (str[i]!=32)
            str[i] = str[i]+ offset;

    printf("\nEncrypted str = \n%s \nlength = %d\n", str, l);

void decrypt(int offset, char *str) {


void main(void) {

    char str[1024];

    printf ("Please enter a line of text, max %d characters\n", sizeof(str));

    if (fgets(str, sizeof(str), stdin) != NULL)
        encrypt(5, str);    // What is the value of str after calling "encrypt"?

        // add your method call here:

So the questions for the homework are listed in the code, but to make it clear that is not what I am after. I want to understand how this program is working so far.


  1. Why write char str[1024]

  2. What exactly is if (fgets(str, sizeof(str), stdin) != NULL) doing? I have a decent idea but I don't know the reasoning behind it.

3.And lastly (I hope) in

if (str[i]!=32)
    str[i] = str[i]+ offset;

why are we worried about str[i] not equaling 32?

I am sorry if this is a lot to be asking but I really truly want to understand this.

Also if you know of any fantastic reads for C please let me know because I am rather worried about the rest of this semester at this point.


Just wanted to say thank you very much to everyone who answered me. I am unfortunately not one of those people who immediately likes to continue asking more questions to acknowledge that you helped me. So for those of you who I didn't directly thank or comment back, Thank you very much. I now have a much firmer grasp on some of the very elementary concepts I was nervous about only 30 mins ago.

A great start would be Kernighan + Ritchie's book,The C Programming Language.
Amazon: here

Also, see The Definitive C Book Guide and List.

For reference, I'm copying this example (nearly) letter for letter from page 18 in The C Programming Language, Second Edition.

#include <stdio.h>
/*count characters in input, 2nd version*/
    double n;
    for (n = 0; getchar() != EOF; ++n)
    printf("%.0f\n", n); /*this never prints*/

I wasn't sure if it was my version of gcc (I'm a noob):

% gcc --version
gcc (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5
Copyright (C) 2010 Free Software Foundation, Inc.


for (n = 0; getchar() != EOF; ++n)
    printf("%.0f",n); /*returns 0123456...n*/

I tried printing "foo" instead of value n, just to see. It still isn't printing.

What am I missing here? I don't like moving ahead while ignoring little problems like these.



So the end result should be:

% gcc ./counter.c -o ./counter
% ./counter

Right now, this is the output from the first snippet:

% ./counter

And the second one:

% ./counter


If you are on an OSX or linux box, you need to type Ctrl+D on its own line to generate an EOF character. On Windows, Ctrl+Z on its own line. Don't type Ctrl+Z on a unix box because that will just send your proces to the background.

You are typing Ctrl+C which is break, and will send a SIGTERM to your program.

On my mac, I get:

$ ./foo

Or if you don't want to signal the EOF condition, use echo and a pipe:

$ echo "hello" | ./foo 

Note that the EOF has to be on its own line. a ^D is printed, and then 6 overwrites the ^, so it looks like the output is 6D.

Of course, in the two above examples, the characters being counted are h e l l o \n. If you don't want a newline, do this:

$ echo -n "hello" | ./foo 

I am a PHP developer, and now I want to learn C for a couple of reasons.

  1. I lack knowledge in Java, as well as data structures and algorithms.
  2. PHP is written in C.

The most important thing is the first reason. I don't want to get deep into C, but at least I could understand what C programs are doing. Does anyone have any good idea how I should proceed? Thanks!

That's probably the wrong approach. First learn the basic theory behind programming which is algorithms and datastructures. These are language neutral.

Than try to learn a language and its syntax to write your algorithms. To answer your question, a good book for C is C in a Nutshell but it DOES NOT teach you the basics of programming.

And then there is still the book The C Programming Language by Kernighan&Ritchie, who invented C.

I am writing a program that accepts a file with database entries in it. The entries are all in the same format, with the data in the same order. The first number in the file is the number of entries. Then the data looks like this: LastName FirstName StudentID age year GPA expectedGraduationDate

Ex: Doe John 12345678 23 freshman 4.0 2013

My issue is with the year value. We are supposed to declare it as type 'class', which is supposed to be enum class{freshman, sophomore, junior, senior, grad};

I have a header file with the following declaration:

typedef enum {firstYear, sophomore, junior, senior, grad} class;

Then my main file:

#include <stdio.h>
#include <stdlib.h>
#include "class.h"

int main(int argc, char *argv[]){

typedef struct{
        int DBrecordID;         //ID for each entry, range 0-319
        char *last;             //student last name
        char *first;            //student first name
        char studentID[8];      //student ID
        int age;                //student age
        class year;             //year in school
        float gpa;              //GPA
        int expGradYear;        //expected graduation year
int numEntries;
DBrecord **record;
char buffer[80];
FILE *fpt;
int c, i;
int j = 0;

//check for invalid file arguments
if(argc != 2){
        printf("Number of arguments is invalid\n");

//error if unable to open file
if((fpt = fopen(argv[1], "r")) == NULL){
        printf("Error: Couldn't open file.\n");

//set file pointer to read passed file
fpt = fopen(argv[1], "r");

//scan first int in file and assign to numEntries
//fscanf(fpt, "%d", &numEntries);

//allocate memory for structures, each is 36 bytes
*record = malloc (sizeof (DBrecord) * numEntries);

//loop through each DB entry
        for(i=0; i<numEntries; i++){
                numEntries = record[i]->DBrecordID;
                        buffer[j++] = c;
                }while(c != ' ');
                        strcpy(record[i]->last, buffer);
                        buffer[j++] = c;
                }while(c != ' ');
                        strcpy(record[i]->first, buffer);
                        buffer[j++] = c;
                }while(c != ' ');
                        strcpy(record[i]->studentID, buffer);
                        memcpy(c, buffer[j++], 1);
               }while(c != ' ');
                        memcpy(buffer, record[i]->year, 4);
                        buffer[j++] = c;
                }while(c != ' ');
                        memcpy(buffer, record[i]->gpa, 4);
                        buffer[j++] = c;
                }while(c != ' ' || c != '\n');
                        memcpy(buffer, record[i]->expGradYear, 4);
}while(c != EOF);

return 0;

*Updated errors

main.c:75: warning: passing arg 1 of `memcpy' makes pointer from integer without a cast

main.c:75: warning: passing arg 2 of `memcpy' makes pointer from integer without a cast

main.c:77: incompatible type for argument 2 of `memcpy'

main.c:83: incompatible type for argument 2 of `memcpy'

main.c:89: warning: passing arg 2 of `memcpy' makes pointer from integer without a cast

main.c:94: parse error before "DBrecord"

So I'm assuming I can't do what I'm trying to do with memcpy, or I'm just doing it wrong. Suggestions?

There quite a few errors in the program but for a start

1) record should be of type DBrecord* not DBrecord**

2) strcpy takes destination as the first argument so this wouldn't work strcpy(buffer, record[i]->last);

3) you also need to allocate memory for record[i]->last

4) strcpy is used to copy strings so if you wan't to store to float or int i.e. gpa etc you need to use memcpy also the value from buffer should be converted using strol strod

also would recommend to get hold of this book K&R it would be really helpful overtime

I found this in a code I am currently studying, could someone explain it to me.

char * string = "Simulated Annealing = 12847369";
char * value = strchr(string, '=');

*(value ++ ) = 0;

printf("%s ==== %s", value, string);

I noticed that string will print in a new line first, why this?

char* karmarkar = "Karmarkar   958572";

I want to use strchr to find the first occurrence of "space" in string karmarkar. How do I do that?

In the first case, strchr will return a pointer to the byte where an '=' is found in string. You need not append 0 to the returned value as it is just another pointer to the character array pointed to by string, which is already null terminated. To print the character, just say value[0]:

char* string = "Simulated Annealing = 12847369";
char* value = strchr(string, '=');
if (value != NULL)
    printf("value: %s, string: %s\n", value, string);
    printf("char: %c\n", value[0]); /* prints = */

Do the same to find a space in the second string:

char* karmarkar = "Karmarkar   958572";
value = strchr(karmarkar, ' ');
if (value != NULL)
  printf("value: %s\n", value);

Always check the return value of strchr before using it, as it returns NULL if the character is not found.

BTW, the statement, *(value ++) = 0 should cause a segfault as it attempts to modify a read-only location. If you found this code in a book that claims to teach C, I suggest that you move away from it and start learning from this. If your compiler generated code that prints a newline for that particular statement, you should start using a better compiler. There are some few good ones available for free download.

I'm trying to assign a function to a variable field, but I get Segmentation fault. Here is the code:

typedef struct node{
    int info;
    struct node *link;
    void* (*make) (int x);

void* make_node(int x)
    node* new_node = (node*)malloc(sizeof(node));
    new_node->info = x;
    new_node->link = NULL;
    return new_node;

int main(){
  struct node *n;
  n->make = make_node;
  return 0;

What could be wrong?

You have forgotten to assign a value to n.

  1. Change the return type of make_node to node*
  2. Do n=make_node(x)

And I strongly advise reading This would be the best thing you can do now.

I'm writing a simple calculation program and I can't get any valid output. All I'm getting is an upside down question mark. Also, I have a prompt at the end of the program to ask the user if they would like to enter in another calculation. However, when I enter a calculation the prompt comes up twice in the console. Does anyone know why these things are happening? Lastly, I can only use getchar and putchar to handle the input and output. Thanks in advance for the help.

int addFunction( int, int);
int subtractFunction(int, int);
int multiplyFunction(int, int);
int modulusFunction(int, int);
float divideFunction(float, float);

int main(int argc, const char * argv[])

int num1 = 0, num2 = 0, result = 0;
char  continuePrompt,  iochar = 0, operator = 0;

do {
    iochar = getchar();

    if ((iochar >= 0) && (iochar <= 20000)) {
        num1 = iochar; 

    if ((iochar == '+') || (iochar == '-') || (iochar == '*') || (iochar == '/') || (iochar == '%')) {
        operator = iochar; 

    if ((num1 >= 0) || ((iochar >= 0) && (iochar <= 20000))){
        num2 = iochar;

    switch (operator) {

        case '+':
           iochar  = addFunction(num1, num2);

        case '-':
            iochar = subtractFunction(num1, num2);

        case '*':
            iochar = multiplyFunction(num1, num2);

        case '%':
            iochar = modulusFunction(num1, num2);

        case '/':
            iochar = divideFunction(num1, num2);



    printf("Would you like to make another calulation? (y or n)");
    scanf("%c", &continuePrompt);

} while (continuePrompt != 'n');
return 0;

int addFunction(int x, int y){
    return x + y;

int subtractFunction(int x, int y){
     return x - y;

int multiplyFunction(int x, int y){
    return x * y;

int modulusFunction(int x, int y){
    return x % y;

float divideFunction(float x, float y){
    return x / y;

Some basics...

A character value '0' does not equal the integer value 0 on in ascii it has the integer value 48. If you're only having each number be 1 digit, it would be something like:

char c = getchar();
// Assuming the user only will input a number...
int number = c - '0';

For reading in an integer with just getchar() I would do something like:

#include <stdio.h>
#include <math.h> // for pow

int getint()
    char c;
    char buffer[255]; // way larger than an integer will ever be I think...
    int numlen = 0;
    int number = 0;
    int x;
    int multfornegative = 1;

    while ((c = getchar()) != '\n') {
        buffer[numlen++] = c;

    for (x = numlen - 1; x >= 0; x--) {
        c = buffer[(numlen - 1) - x];
        if (c == '-') {
            multfornegative *= -1;
        } else {
            number += (c - '0') * (int)pow(10, x);

    return number * multfornegative;

for output you would do something like...

void putint(int number)
    char digit;
    int x;
    int start;

    if (number < 0) {
        number *= -1;

    start = log(number) / log(10);

    for (x = start; x >= 0; x--) {
        digit = ((number / (int)pow(10, x)) % 10) + '0';

Also, try to break apart your input, the way you have it in the loop ends up confusing which is messing up your logic.

int num1;
char op;
int num2;
int ans;

do {
    num1 = getint();
    op = getchar(); getchar();
    num2 = getint();

    switch(op) {
        case '+': ans = num1 + num2; break;
        case '-': ans = num1 - num2; break;
        // And so on...
while (1);

The C Programming Language is an amazing book to read for learning C, written by the inventors of C themselves.

Is there some sort of "Learning C for developers of other languages" book or tutorial available?

I am currently trying to learn C (not C++, maybe later) and even though I had some experience with it (had it in school writing DOS Applications using Borland C...), I don't know much about the standard library or about the "architecture".

My current project - which I want to use to learn - is to write an Ogg Theora player. That is, using the libogg, libvorbis and libtheora in my project. But here I already have a problem: How do I link them?

I am a C# developer, and in C# I would just add a reference and be fine. But in Visual C++ (the compiler/IDE that I will use in any case because the project that I really want to do much later depends on an existing C Visual C++ project), I am simply overwhelmed with the project properties.

I did find a lot of resources about C, but much stuff is really basic stuff (explaining what functions are - I know what a function is, I'd just like to know how a function can differ between C and C#/Java) or really academic (the kind of stuff I would read to get sleep, but not to learn something from it).

I found this book useful, but I am also looking for something more concise aimed at existing C#/Java/PHP/Whatever developers, and also about using Visual C++ 2008.

Any good hints?

Why don't you use something that's more lightweight and simpler to use than visual Studio for your C Projects?

I reccommend Code::Blocks. Believe me, it's a lot more lightweight than Visual Studio, and in my opinion it's a lot better to work with it whilst learning to develop in C.

As regards books, I would go for both K&R's C Programming Language, but I also reccomend another one : C Primer Plus and I think the latter one is more appropriate as a beginner's book.

It seems when I try to research all I can find are how many lines are in Linux, call of duty, windows and other things that are massive applications with millions of lines of code.

Does anyone have examples of code size of applications that don't take teams and teams of people?


I'm 24 yrs old and just starting to learn I feel like I got a really late start but I'm tired of sales and love technology so I'm just looking for something to gauge by.

Thanks in advance!

If you're new to programming, you might want to start with a great book and a number of practice problems. I'd recommend starting with C.

For these types of problems, you can write solutions which are 20-100 lines long. You can write the infamous "Hello World" in a mere 6(ish) lines. It is pretty rare that an individual works on something in their own spare time that is greater than a few thousand lines of code at most. Especially a beginner.

Good luck!

I've been trying for about 5 hours to get this code to work properly, and the code is written based on hours of internet research. I have modified it several times, all of which gave me segmentation faults, so this is the only version that runs. What is happening, is that the code is cycling through, and deleting not only the element you want to get rid of, but all elements preceding it. So, if you want to delete the last element, everything in the list goes. Or, if you wanted to delete the second element, the first and second go, and so on. It thinks that every name entered is the top name for some reason.

static void menu_delete_employee(void)
  char deletename[MAX_NAME_LENGTH+1]; 
  char namecheck[MAX_NAME_LENGTH+1]; 
  int errorcheck = 0;
  int foundit = 0;
  fprintf(stderr, "Enter the name of the employee you wish to delete\n");
  employee_list = top;

    strcpy (namecheck, employee_list->name);
    printf("namecheck = %s\n", namecheck);
    errorcheck = (strcmp (namecheck, deletename));
    printf("errorcheck = %i\n", errorcheck);

    switch (errorcheck)
      case 0:
          printf("This is the right name\n");
          foundit = 1;
          if (employee_list->prev == NULL)
            printf("top name\n");
            top = employee_list->next;
            if (employee_list->next == NULL) 
              printf("last one\n");
              temp = employee_list->prev;
              temp-> next = NULL;
              free (employee_list);
              printf("somewhere in the middle");
              temp = employee_list->prev;
              temp->next = employee_list->next;
              employee_list->next->prev = temp;
              free (employee_list);
          printf("delete successful\n");
          printf("not this one\n");
          errorcheck = 0;
          employee_list = employee_list->next;
  while (foundit == 0);
  if (foundit == 0)
    printf("Name not recognised\n.");

Any help would be much appreciated.

Maybe the doubly-linked list is not built up the way you think it should. This has to be checked first.

Assuming the topology is correct, there are still a couple of issues with this code:

employee_list->name; (just above the do loop): what is this?

strcpy (namecheck, employee_list->name); : you do not need to copy, this is just a shorthand, so namecheck could be a (const) string pointer.

switch (errorcheck) : this has only 2 arms, why don't you use an if ?

if (employee_list->prev == NULL) ...: you just move the top pointer here but do not delete the top item, this will cause memory leaks. You also do not set the prev pointer of the next-to-top item to NULL.

In the "somewhere in the middle" part: you free employee_list which is the current position pointer. The next item to be processed should be temp->next, right? This is probably your problem because you do not take care of moving the current pointer along. Moreover, it is much better to set a pointer explicitly called tobedeleted to the item to be deleted, make sure the pointer used to iterate along the list (employee_list in your case) is moved appropriately, and when *tobedeleted is appropriately isolated out from the doubly linked list then issue the free(tobedeleted) command.

employee_list = employee_list->next; : you should check for employee_list turning into NULL at the last item, and exit the loop. Otherwise Bad Things will happen.

Final advice: you really need to consult a good C book... Kernighan and Ritchie for instance. Way better than "Internet research".

Please explain what does this VC++ code do? Is it possible to convert this code to Delphi2010?

void CDMOnLineView::OnActionGetdata()
    bool retCode;
    DWORD retByte = 0;
    int TmpHigh, TmpLow;
    UCHAR HIDData[64];
    int LastX, LastY;
    UCHAR Button;
    CDC* pViewDC = GetDC();

    if(yPos > 500) yPos = 0;
    else yPos = yPos + 16;  

    if(hDriver == NULL)
        pViewDC->TextOut(10,yPos,"Driver not connect yet.");
        IO_Param.CallerHandle = m_hWnd;
        IO_Param.Model = DM_A4;
        retCode = DeviceIoControl(hDriver, IOCTL_DM_READ_DATA, &IO_Param, sizeof(DM_PARAM), HIDData, 
                                6, &retByte, NULL);
            if(retByte != 0)
                Button = HIDData[1] & 0x01;
                TmpLow = (int)HIDData[2];
                TmpHigh = (int)HIDData[3];
                LastX = (TmpLow & 0x00FF) | ((TmpHigh << 8) & 0xFF00);
                TmpLow = (int)HIDData[4];
                TmpHigh = (int)HIDData[5];
                LastY = (TmpLow & 0x00FF) | ((TmpHigh << 8) & 0xFF00);
                sprintf(szStringBuffer, "Button: %d, X: %.5d, Y: %.5d", Button, LastX, LastY);
                pViewDC->TextOut(10,yPos,szStringBuffer, strlen(szStringBuffer));
            else pViewDC->TextOut(10,yPos,"Return bytes incorrect.");
            ErrorCode = GetLastError();
            sprintf(szStringBuffer, "Call IOCTL_DM_READ_DATA fail. Error: %d", ErrorCode);
            pViewDC->TextOut(10,yPos,szStringBuffer, strlen(szStringBuffer));


What the DeviceIocontrol function will do? Please try to explain the parameters also.

thanks all.

The DeviceIoControl function is documented at MSDN. User mode programs use it to interact with device drivers.

Converting this code is pretty simple. The call to DeviceIoControl maps across trivially. The only area that you are likely to struggle with is the C bitwise operations. If you don't have a copy of K&R to hand, then you should!

I am new to C and just starting to learn how to use it. 3. I need to write a program which prompts the user to enter an integer (in the range 1-8) determining picture size and then uses functions which call writePattern to draw each of the following pictures.

I previously created a rectangular "comment" box that I had to make, but these simple drawings are more complex and I am unsure how to do them. I am also new to StackOverflow so I will post my code into a pastebin link rather than putting the code on here because I do not know how to do so properly.

Here is the code I am working on:

As you can see in the code, drawBox, drawSlantRight, drawSlantLeft, drawTriangle, drawX, and drawXmasTree all need to be completed by me. I feel like they probably all have a similar connection as far as doing them. It probably involves a bunch of loops, however I have no idea how to set it up. If someone could show me how just one of these is done, then I feel like I will be able to get the rest. Hope you can help. Heard this was a great website for programming help. Thanks!

These functions are classic getting-started functions to get use to working with loops and simple programming logic. Since you have no idea on how to do them, I am gonna show you how to do the first function. You will get an idea on what needs to be done, and I recommend that you try the others out personally. Its the only way you will learn!

/* draws a square box with chars '*' and '.'.  For example if the
   parameter value is 3, the following box would be drawn.

    void drawBox(int size)
        int line_counter;
        for (line_counter = 1; line_counter < size+1; line_counter ++)
         int star_counter;
         for (star_counter = 0; star_counter < line_counter; star_counter ++)

         int dot_counter;
         for (dot_counter = line_counter; dot_counter < size; dot_counter ++)



Try that, it should work. So basically there is the gist of it. Like I said, you need to meddle around with for loops, counters and print statements.

Since your getting started I have listed some resources you might be interested in. For a good tutorial on C, try this site. Furthermore, if you want to invest more in this study, I would highly recommend getting The C Programming Language, available at all good book shops (no commercial ad intended). Its co-written by Dennis M. Ritchie (The creator of C).

may i know how to get into c programming.that is may i know a specified path

If you really want to learn C you should get a book by K&R on C called The C Programming Language. Other books are fine too.

If you simply want to play around and make a few small programs, you can simply search Google for millions of tutorials.

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include stdlib.h>
#include <string.h> 

#define LB_SIZE 1024

int main()(int argc, char *argv[])
     char full Pathname[] = /usr/X11R6/bin/xeyes;
     char *myArgv[LB_SIZE];  

     myArgv[0] = malloc(strlen(fullPathName) + 1);
     strcpy(myArgv[0], fullPathName);
     myArgv[1] = NULL;  
     execvp(fullPathName, myArgv);


As @Als has said, strings should be enclosed in "mystring text" quotes.

I really think you need to start learning C before coding in it. Here are some recommendations:

If you don't want to buy a book, try this free wikibook. I actually contributed a chapter to it, so please give it good ratings :).

The following bit of code in C is supposed to append a number at the end of a list. We have the following struct for the list:

struct element
   int value;
   struct element *next;

And the following code for the Append function:

void append (struct element **l, int value)
   struct element *tmp = *l;
   struct element *new = (struct element *) malloc (sizeof (struct element));
   new->value = value;
   new->next = NULL;

   if (tmp == NULL)
   *l = new;
      while (tmp->next != NULL)
          tmp = tmp->next;
      tmp->next = new;

I don't understand the use of pointers in the code above, in particular, I have no clue why l appears sometimes with two asterisks, and sometimes with one, and why tmp appears sometimes with an asterisk and sometimes without. I also don't understand where the asterisk appears as a dereferencing operator and where it serves for defining pointers. I have read an introduction to pointers in C but couldn't wrap my mind around pointers in this code anyway. Help appreciated.

You've gotten pretty good answers already, I'd add a strong personal recommendation for The C Programming Language, 2nd Edition by Kernighan and Ritchie (K&R). The chapter on pointers will clear this up for you nicely.

I am using Visual Studio 2013 to try and learn C language.

I'm using the famous K&R book and after literally copying and pasting the following piece of code from the book to Visual Studio 2013 i got the error :

1 error C2106: '=' : left operand must be l-value
2 IntelliSense: expression must be a modifiable lvalue

#include <stdio.h>
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
/* count lines, words, and characters in input */
    int c, nl, nw, nc, state;
    state = OUT;
    nl = nw = nc = 0;

    while ((c = getchar()) != EOF) {
        if (c == '\n')
        if (c == ' ' || c == '\n' || c = '\t')
            state = OUT;
        else if (state == OUT) 
            state = IN;
    printf("%d %d %d\n", nl, nw, nc);

it seems the error comes from the statement :

if (c == ' ' || c == '\n' || c = '\t')

But i really can't figure what's wrong, not mentioning the fact that the code is straight from the book.

Any help would be greatly appreciated !

Thanks !

if (c == ' ' || c == '\n' || c = '\t')
//                             ^ Oops.

I suggest you take a break. Even without knowing that the assignment would try to write to the result of || because it has lower precedence, the discrepancy is screaming.

I just started in C programming and I know that "%d" defines that it will be a number value, as in:

int x = 9;

printf("X = %d", x);
return 0;

but what are the other variable specifiers for C? (to define strings, and do they change for float, double, long, etc.?)

You may want to pick up a copy of Kernighan and Ritchie's The C Programming Language. It short but fully packed. Working through this book is well worth the time.

But as to your question, you're asking about Format specifiers for string literals. You'll probably also want to look at escape characters soon (e.g. \n for new lines). Fortunately, it's all in K&R (the above book), specifically on page 153 (2nd edition).

When I compile my code I get the following warning:

main.c:8:13: warning: assignment makes pointer from integer without a cast [enabled by default] Contents = getc(fp);

Why do I receive that warning?

char* readfile (char* fileName){
  char* contents;
  FILE* fp;
  fp = fopen(fileName,"r");
  while(getc(fp) != EOF){
    contents = getc(fp);
return contents;

Although R Sahu's answer is technically, using an int where a char* is more accurate is probably not the best idea.

The problem, which Ghosh correctly pointed out, is that you are trying to assign to contents (a char*) the return value of getc() (an int). In order to fix this problem literally all you need to do is change line 6 to *contents = getc(fp);

However you also do not allocate any memory to contents. This would be done with char * contents = new char*[MAXLENGTH]; where MAXLENGTH is the maximum length you expect to be stored in contents. If you do not know how long the character array will be, then use a resizable array.

I'm just going to leave this as a resource for you since it shows how to correctly write this code, and is IMO the best book on C ever written.

how to learn c basic easily and quickly?

The C Programming Language (also referred to as K&R):

Amazon: The C Programming Langauge - Second Edition

Pick up a copy and start reading. It teaches the basics right from the start and builds on top of them quickly.

I' m trying to understad the work with a pointers. So I've wrote a test program where name is split into labels by removing the separating dots. Each label is represented as a length/data pair as follows: represents as "x\06googlex\02ru" I get signal SIGABRT when i returned from my test function I guess it's caused with my bad work with pointer.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void test(unsigned char* dns, unsigned char* host);

int main(int argc, const char * argv[])

    unsigned char host[]="";

    unsigned char* dnsTest=(unsigned char*)malloc(20);


    test(dnsTest, host);

    printf("%s", dnsTest);


    return 0;
void test(unsigned char* dns, unsigned char* host)
    strcat((char*)host, ".");

    int lock=0;

    for(int i=0; i<strlen((char *)host);i++)



            for(;lock<i; lock++)



Since you tagged c++ as well, you can use new \ delete instead of malloc \ free. New will call constructor (when you will learn classes it will be useful), and new return to you exact type, so no need to cast (and casting is almost always a bad idea)

Then assertion after memory allocation with new will be redundant:


since c++ new will throw an exception by default. If you go ahead, you can use std::string - its much more simple than c null terminated strings (but not for the task of understanding pointers).

Every other comments (about redundant strlen usage and absence of '\0' symbol) is correct too, but I want to give you two advices, how to grasp pointers.

First - read K&R - it's the Bible.

Second - if you use Microsoft Visual Studio, you can compile your code in Debug mode, and use Memory View tab. Visual Studio compiler place some magic number inside memory (link) at debug mode. They can help you with understanding where you addressing unallocated memory or how exactly your memory layout looks like.

I have a code in C .

    int a; 
    a =10;
    printf ("%d", &a); 

I want to know if some garbage will be printed or error msg will be shown. Basically I am interested in knowing how printf works. Does it have a list of variables in a table sort of things. If a table is there from where it will take the value of &a

This is a beginners question and deserves to be answered properly. (I'm startled by the downvotes and the non-constructive comments)

Let me give a walk-throu line by line:

int a; 

The first line declares a variable with the name a. The variable is of type integer and with normal compilers (Microsoft Visual C++ on Windows, GCC on linux, Clang on Mac) this usually 32 bits wide. The integer variable is signed because you did not specify unsigned. This means it can represent values ranging from –2,147,483,648 to 2,147,483,647.

a =10;

The second line assigns the value 10 to that variable

printf ("%d", &a); 

The third line is where you get the surprising result. "%d" is the "format string" it defines how the variables, given as further arguments are formatted and subsequently printed. The format string comprises of normal text (which will be printed normally) and control-sequences. the control sequences start with the character % and end with a letter. The letter specifies the argument type that is expected. d in the above case expects a integer value.

The problem with your code is that you do not specify an itenger value, you give the address of an integer value (with the address-of & operator). The correct statement would be:

printf ("%d", a);


I recommend that you have a read on a good C book. I recommend "The C programming language" which is from the original authors of the language. You find this book on amazon, but you find it also online.

You can find the same answers reading in the standard. But to be honest, these documents are not easy reading. You can find a draft of the C11 standard here. The description of the formatting options starts on page 309. (drafts are usually good enough for programming purposes, and are usually available for free).

I'm writing a code which shows the largest of entered numbers, but when run it returns a seemingly random number, my code below:

#include <stdio.h>

int main() {
    int largest;
    int nvalue;
    int no1, no2, no3;

    printf("Enter value of n:");
    scanf("%d\n", &nvalue);

    printf ("Number1:");
    scanf("%d\n", &no1);

    scanf("%d\n", &no2);

    scanf("%d\n", &no3);

    largest == nvalue;
    if (no1 > nvalue) {
        printf ("The largest number is:%d\n", &no1); }
    else if (no2 > nvalue) {
        printf("The largest number is %d\n", &no2); }
    else if (no3 > nvalue) {
        printf("The largest number is %d\n", &no3); }
    else {
        printf("The largest number is %d\n", &largest); }

    return 0;

when run it returns:

Enter value of n:3

Can you tell me what I'm doing wrong? Thanks The largest number is -1536115152

Code should be well formatted e.g code inside curly braces ({ }) should be indented properly (this makes it easier to read your code).

#include <stdio.h>

int main(int argc, char *argv[])

Variables should be descriptive (helpful if other people are reading over your code).

    int largest = 0;
    int num1 = 0, num2 = 0, num3 = 0;

The newline character ('\n) isn't necessary, unless you want scanf to take the newline character as part of your input.

    printf("Enter the first number : ");
    scanf("%d", &num1);

    printf("Enter the second number : ");
    scanf("%d", &num2);

    printf("Enter the third number : ");
    scanf("%d", &num3);

This is a much cleaner and simpler check to see which is the largest number. (taken from Rishav Choudhuri's code above)

    if (num1 > num2 && num1 > num3)
        largest = num1;
    else if (num2 > num1 && num2 > num3)
        largest = num2;
        largest = num3;

    printf("The largest number is : %d", largest);

    return 0;

I also recommend reading this book The C Programming Language 2nd Edition and reading some tutorials online

also be sure to write lots of code as well :D

int a{7}={1,2,3,4,5,6,7};
int len=sizeof(a)/sizeof(int);
int a=len/2;
for(int i=0;i<2;i++)
  for(int j=0;j<a;j++)

The problem is I am getting an error when I divide the lenght by 2. Please give me a solution.

You declared the array wrong, correct way:

int a[7]={1,2,3,4,5,6,7};

Also you cannot declare two as rename the second:

int a=len/2; 

to something else.

Might I suggest some good C Books? I think you need to learn C before coding in it.