char pointers and scanf()

Hello. More questions about pointers coming:

If I have the following code:


char * userName;
printf("%s", "Enter your name: ");
scanf("%s", userName);
printf("%s", userName);


This codes asks the user for his/her name and reads the input, then it prints the name to output. However, with the code above, I get the debugger after I enter my name and press Enter.

I'm aware that if I changed the first line from a char pointer to a char array then this code would work fine -- but I'd like to understand why this is the case.

I'm sure it's possible that some concept related to the cause of this problem has been covered in one of my previous posts on pointers, but I skimmed through them and couldn't find anything that I could recognize as applicable (although I'm sure it was there somewhere). Could anyone please help me understand why scanf() doesn't work with the char pointer -- why it would work fine with a character array and not with the character pointer?

Thank you for your help.

MacBook, Mac OS X (10.5.8)

Posted on Oct 8, 2009 1:34 AM

Reply
29 replies

Oct 10, 2009 4:44 PM in response to etresoft

Schools don't teach assembly anymore.

Writing in assembly really does give a solid foundation in what a computer can and can not do, and there is a whole lot less confusion about abstract data types.

It is even more interesting when you are writing on raw hardware with no operating system, and you need to do it all for yourself.

Ah, the good old days 🙂

But the only way to really learn programming is to write programs. Lots and lots of programs. If you can afford to throw away the first copy and do it again, you learn even more as you apply new things you learned.

Write little programs just to see how some library routine works. Use gdb to single step the code and see what each statement does, looking at variables along the way.

Actually I recommend working your way through "The Unix Programming Environment", by Brian W. Kernighan and Rob Pike.

I also personally like "The C Programming Language", 2nd Edition, by Brian W. Kernighan and Dennis M. Ritchie. Code up some of the example C code. You will learn a lot from both the book, coding and running the examples.

I think Brian Kernighan is one of the best programming book writers. His books are not verbose, but they pack a huge amount of information in very few pages. The examples alone are invaluable.

Oct 10, 2009 6:56 PM in response to etresoft

etresoft wrote:
RayNewbie wrote:
this kind of discussion needs two people in the same room with a white board (and maybe a pizza as well).

etresoft wrote:
When is that going to happen?

Time to issue the !!_Dev Forum Challenge_!! Who will be the first to iChat Tron?
You are glossing over a huge issue. How does anyone learn programming? Not in a big lecture class.

Yeah, that's true. Learning to program is ultimately a very solitary activity, and maybe we don't start to become programmers until the first 30 hour session without food or drink. We must die alone, write books alone, and learn programming alone.

I do feel suitably glossy. My defense attorney (if he hasn't quit the case by now) might argue that the context was about basic computer science, not programming per se. I want to see Tron sitting through some lectures then taking a midterm on the Turing Machine, how the stored program digital computer emerged from that concept, and how modern computers then evolved. After that course, I think there's a good chance he might understand why scribbling all over your memory is a bad thing.

The real payoff here is that Tron will then teach others!! That's what he likes to do--same as you and I. So sending him off to computer science classes is actually a contribution to science and a demonstration of good citizenship. Not unlike G.W. Bush, I know these gifts won't be recognized in my lifetime, but that's never stopped me in the past.
I much prefer answering Tron's questions than the old "I spilled soda pop in my Macbook Pro and now it won't turn on!"

Well said, Et!! It's an honor to be on the same page with you. Btw, I've found that Pepsi does the most damage for some reason.
Don't expect to learn anything about memory allocation in a C# class.

I think C# is the only place you can go after VB. I suspect the Master Plan is to do enough brain damage on a global scale that MS is left owning the only living system programmers. Yeah, I know it's paranoid, but that's not my primary mental disorder. More importantly, that diagnosis doesn't prove my suspicions have no basis in fact.
The squeaky wheel gets the grease.

Tron has also read the help and knows some tricks that other OP's can't seem to manage.

\- Ray

Oct 10, 2009 7:25 PM in response to BobHarris

BobHarris wrote:
Actually I recommend working your way through "The Unix Programming Environment", by Brian W. Kernighan and Rob Pike.

Yesss!! Nice catch, Bob! From memory, the first project in that book is to write a shell. Prior to doing that project, I thought anyone who could write a shell was some kind of god. The code is so clear you almost don't even need the text. That one project is a classic that taught me so much I was hard to live with for several weeks (actually never quite recovered). The shell doesn't quite do everything that bash does, but at least you don't need to escape every other command line char to grep for something.
\- Ray

Oct 11, 2009 1:17 AM in response to etresoft

etresoft wrote:
Then you have two actions. You are allocating the pointer, but not initializing it. Then you assign a value to the pointer. It is more wasteful in lines of code than anything else. One of the things that keeps Objective-C simple is that objects are always pointers. Pointers are simple data types and very easy to deal with. The above two statements in C++ would be an entirely different discussion.


Understood. Well, more or less.

I much prefer answering Tron's questions than the old "I spilled soda pop in my Macbook Pro and now it won't turn on!"


And that was going to be my next thread...

Don't expect to learn anything about memory allocation in a C# class.


Even I know that much. I have experience with C#, and while its simplicity could be nice at times, it always left me feeling empty -- like someone else had done all the work for me and I wasn't even really programming. Same thing with VB, of course, but that goes without saying. That's where I started programming, unfortunately, so maybe the implied brain damage that comes with those languages is why you guys can't seem to get some of these concepts through my head. I didn't spend very long with them, though -- just enough to learn the basics of programmging (variables, loops, branching, ect.), so there may yet be some hope.

The squeaky wheel gets the grease. As long as you get good answers here in the forums, keep asking questions.


I plan on it. 🙂

But seriously, thank you for the encouragement. It's always important to me to know I'm not getting under anyone's skin too badly around here. I do still agree with what Ray said in his last post -- I'm not getting anywhere hacking away at issues that I'm not even really capable of understanding at this point. I want to try to keep things more relevant. That being said, you can always count on a new Tron thread popping up every few days (or minutes)...

Try to find a good computer science program to enroll in too. You will learn a lot there.


I've done that. I'm still 22, and I spent the first few years after high school doing things that weren't conducive to, well... anything. So, after getting my life on track, I finally enrolled at a community college (CCBC -- Community College of Baltimore County). At the time I had just started messing around with programming in Visual Studio a bit, and my other interest was chemistry (still is, to an extent) -- I ended up choosing Computer Science for a major because, as much as I loved chemistry, I've never come across a hobby that was nearly as satisfying to me as sitting at a computer writing line after line of code, so I chose that path, and I'm glad I did.

Anyways, at CCBC, I haven't been incredibly impressed with the Computer Science program (although it hasn't been that bad). Besides the wonderful CINS 101 class and the data communications class that didn't interest me all that much -- the only programming or even compluter-related courses that the AA degree I'm going for requires are Introduction to Unix, Introduction to OOP, Introduction to Visual Basic 2005, and Introduction to C++. I've already taken them all. The Visual Basic class was... well, Visual Basic. The introduction to OOP class was about as abstract and unenlightening as I could imagine a class on programming ever being (you can tell from my incredibly novice threads on Objective-C that, despite the course in OOP, I don't understand these concepts well). Also, instead of teaching OOP in the context of a real, tangible language, the course used pseudocode -- and I don't know how anyone else here feels about that, but I think it's the most grand waste of time imaginable. I was never able to apply any of the OO concepts I learned to programming because there was no programming -- no compiler, no language -- just psuedocode.

Anyways, the Unix course and the C++ course were actually pretty good (although I've forgotten and am in the process of re-teaching myself most the Unix material). They were helpful to an extent. But, as I'm sure you guys can tell from the nature of my questions and threads, I should probably be just a bit further along in things having taken all these courses (and getting A's in them, so it's not like I wasn't doing the work or anything).

Now that I've taken all the fun stuff, I'm stuck with all the other random courses necessary for an AA degree (English and Spanish and health and science courses and what not). I've gotten most of them knocked out of the way. Right now I'm taking Calculus I, which is turning out to not be a great deal of fun, and I still have Calculus II and Discrete Mathematics after that.

Anyways, sorry to bore you guys with all that. I guess my point is, I haven't had the best experience with programming classes, and combining that with the fact that I truly enjoy and tend to do better with learning things on my own, I've just been sticking to hitting the books recently. I wouldn't mind, however, doing what Ray mentioned in the last post and just trying to find a separate class to take at a different campus or something, strictly for the sake of my programming skills (and not toward an AA degree or something like that). I hadn't even considered that option, but I think it might be helpful.

After I get the AA at CCBC, I intend to go to UMBC, where I'm told they have an excellent Computer Science program, so I've kind of been holding off my hopes at actually learning something from a real class until then.

Anyways, sorry to bore you will all that stuff -- I guess I'd just really like to hear any input from you guys who've been through it all, you know -- the classes and the Computer Science programs and what not. So if you have any more input or advice, send it this way!

Oct 11, 2009 1:26 AM in response to BobHarris

BobHarris wrote:
Writing in assembly really does give a solid foundation in what a computer can and can not do, and there is a whole lot less confusion about abstract data types.


I've been interested in assembly language since day one of programming for me. There's something fascinating about getting down to the core of things. That brings up a question I have:

If I want to try to learn a little Assembly some day down the line, am I restricted to this 80x86 Assembly Language? I don't even really know what that is, but it's the only version of the language that I can find any books on. I was told that 80x86 is like assembly language for Windows or something (is that right?). If that's true, is there a Mac version. How's that work? Are there any good resources for going about learning assembly language in the direction of Mac OS X? I was given a few good links in a previous thread and I still have them bookmarked, but I just wanted to ask...

Actually I recommend working your way through "The Unix Programming Environment", by Brian W. Kernighan and Rob Pike.


I'm going to have to look into that. I working through a book on Unix right now, and it's a pretty good one, but I'd like to give one by Kernighan a try, since the K&R C book is so good.

I also personally like "The C Programming Language", 2nd Edition, by Brian W. Kernighan and Dennis M. Ritchie. Code up some of the example C code. You will learn a lot from both the book, coding and running the examples.


Yeah I have that book -- it's excellent, definitely. I've only gotten about 20% or so through it because I'm working through so many other books right now, but everything I've read so far has been great. On that note, I've been wanting to ask: there's a companion book to K&R called "The Answer Book" or something like htat -- has anyone read this? Is it any good? Or, rather, is it worth buying and reading through?

Oct 11, 2009 2:09 AM in response to RayNewbie

RayNewbie wrote:
Time to issue the !!_Dev Forum Challenge_!! Who will be the first to iChat Tron?


hehe

I want to see Tron sitting through some lectures then taking a midterm on the Turing Machine, how the stored program digital computer emerged from that concept, and how modern computers then evolved. After that course, I think there's a good chance he might understand why scribbling all over your memory is a bad thing.


Yes, there's a good chance, but who can say for sure?

Maybe Tron just likes to scribble...

The real payoff here is that Tron will then teach others!! That's what he likes to do--same as you and I.


You're right about that. I do like to teach others, and I wish I knew enough that I actually could (although that doesn't stop me from trying every now and then -- it's always nice when those newbie threads pop up).

So sending him off to computer science classes is actually a contribution to science and a demonstration of good citizenship. Not unlike G.W. Bush, I know these gifts won't be recognized in my lifetime, but that's never stopped me in the past.


That's right, isn't that what they say? -- the best work is only appreciated posthumously. 🙂

I think C# is the only place you can go after VB.


It's funny -- you never even really hear the words C# and VB around these forums. They're like four-letter words. I mean, back when I first started programming on Windows with Visual Studio, VB and C# were your options as far as I knew, and there was Visual C++ (and the J# language, if you can call that an option). I learned some C++ and programmed it in console apps using the Visual Studio compiler, but that's as close to real programming as a I got. Luckily, I only went down that road off and on for about a year, at which point I turned more steadily toward C++. Then, in last few months, I took up the hobby I've wanted to take up for about two years now -- Mac programming! The last time I tried programming on the Mac as a little kid, it was all CodeWarrior and ResEdit and what not, and I never even understood that, so when I downloaded Xcode for the first time a ways backs I was kind of lost. But I eventually decided to stick to it recently, and with the help of these forums, I've actually got a slight idea of what I'm doing now. And moreover, it's the first time I've ever felt like I'm doing real programming, if that makes any sense. Maybe it's just the low-level nature of C that gives me that feeling -- I don't know, but I feel like I actually have some control over what's going on behind the scenes now (or rather I could have that control if I was better at it), whereas with C# and VB, I didn't feel like that at all.

Anyways, right now I've got four projects going. The first is my continued quest to understand the depths of C. The second is my beginning quest to learn Objective-C and Cocoa and, in the process, get a better understand of OOP. The third is Unix and the command-line and what not (right now I'm still at the beginning, working with redirection and pipelines and so forth). And the fourth is HTML / XHTML, which I've taken up out of hobby, but more so because I'd like to be able to design some basic web sites so I can bring some money into my house. My sights are set on other things down the line, like Java, Python, SQL and databases, XML, and getting back to C++, but for now I'm trying to take it one thing at a time (or, well, four things at a time I guess).

Also, thanks to Keith for the recommendation on the Kernigham and Plauger book. I'm going to check that one out. Never hurts to add another book to my endless library, especially if it's a good one.

Anyways, thanks to all of you for your help around here. You guys are great.

Tron out.

Oct 11, 2009 7:25 AM in response to Tron55555

Tron55555 wrote:
If I want to try to learn a little Assembly some day down the line, am I restricted to this 80x86 Assembly Language?


Not really. If you want to really run assembly code on your Intel Mac, then yes. But there are lots of emulators for simpler processors. I first wrote assembly on my brother's Timex Sinclair 1000 with a Z80 processor. Then in college, I had a wacky professor in Operating Systems class who insisted we do everything in assembly on the old IBM 4381. These days, you can run that system under an emulator for MacOS X.

I was told that 80x86 is like assembly language for Windows or something (is that right?). If that's true, is there a Mac version. How's that work?


The x86 and DOS/Windows have a similar provenance - hacked up over the years to maintain backwards compatibility with very good performance. Apple always preferred the Motorola chips that always had a much cleaner design. Funny how things turn out.

Oct 11, 2009 7:33 AM in response to Tron55555

Tron55555 wrote:
It's funny -- you never even really hear the words C# and VB around these forums. They're like four-letter words.


I played around with .NET a few years ago. I thought is was pretty nice and a great improvement over MFC. I find the .NET architecture very similar to Cocoa. I don't know how robust it is for real projects. All the multi-billion dollar boondoggles seem to be .NET-based. Microsoft doesn't even use it for their own projects.

Oct 11, 2009 8:34 AM in response to RayNewbie

I've been interested in assembly language since day one of programming for me. There's something fascinating about getting down to the core of things. That brings up a question I have:
If I want to try to learn a little Assembly some day down the line, am I restricted to this 80x86 Assembly Language? I don't even really know what that is, but it's the only version of the language that I can find any books on.

As to books, it is a Mass Market thing. Windows on intel chips has is such as big market, and has been around so long, it gets more books written about it. If you have a CPU architechure you are interested in, you can most likely find something on the Web published about it. Sometimes the only books are the ones writting by the manufacture of the CPU.
Where there are other CPU architechures, many have fallen by the way side, and unless you are going to be actually using another kind of computer with a different CPU chip, then x86 is what you have to play with.
You can get emulators for other CPUs. For example, my first assembly was a PDP-8. It had 8 basic instructions, and only 4K of memory. There are emulators for the PDP-8, that include all the software you need to play with assembler.
There are other CPU emulators around as well.
But the problem with emulators is that you are unlikely to write anything you are actually going to use. And I find that writing a bit of code that I actually can use, it much more powerful as a teach tool.
Writing code for an emulator that you are not going to use anywhere, has the benefit of comparing and contrasting different ways of doing things, but I just do not have as much interest in it in the long run.
Using an emulator as part of a class is OK, as it gives me a goal (getting a good grade and learning the course concepts). But I do not continue playing with the environment unless I have a day to day use for it.
Another reason that you do not see much about assembly language is that in many ways, C has replaced assembly as the low level language. As you are seeing C does not really restrict what you can do with memory, while at the same time giving easier to read statements such as 'if/elseif/else', 'for', 'while', 'do/while', 'switch/case', etc... statements, and structures for aggragating data. Plus C is semi-portable across multiple CPU platforms. It is a lot of work to port C to a different CPU platform, but moving Assembly is a total rewrite.
However, C still hides a lot of the under lying nature of the CPU and Memory, which is why you are trying to understand pointers, stacks, arrays, memory bounds, etc...

I was told that 80x86 is like assembly language for Windows or something (is that right?). If that's true, is there a Mac version.

Today, both Windows PCs, Mac OS X, Linux, FreeBSD, NetBSD, a version of Solaris, and several other operating systems run on the intel x86 CPU chips. And it is the CPU that dictates what the assembly language looks like.
So x86 assembly is what you would learn for Mac OS X, assuming you are using an intel based Mac, and since your signature says MacBook, that would be an intel x86 based CPU chip.
And yes there is an assembler that run on Mac OS X


man as

How's that work? Are there any good resources for going about learning assembly language in the direction of Mac OS X? I was given a few good links in a previous thread and I still have them bookmarked, but I just wanted to ask...

For basic assembly language, and for assembly language that calls standard C library functions, you can use just about anyone's book on assembly as long as you read things with a "Grain of Salt", as there may be little differences you have to adapt to.
I would write little bits of C code and then tell the

gcc

compiler to generate the assembly output, and then compare that assembly against your C code. At first I would use "Unoptimized" code as it will make things easier to analyze.

#include <stdio.h>
main()
{
printf("hello, world
");
}

Compile it, but stop after generating the assembly code:


gcc -S -O0 hello.c # that is "dash Capital O Zero"

And you will get a hello.s file


.cstring
LC0:

.ascii "hello, world

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

char pointers and scanf()

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.