Quote:
Originally Posted by j0hnsmith
Can someone please explain to me the first program works and the second one doesn't.
|
A char* doesn't point anywhere until you give it somewhere to point.
Code:
char currency[80]; // array
That is a buffer that can hold up to 80 characters.
Code:
char *currency; // pointer
but that is just an uninitialized pointer.
I'm not sure what you're trying to do. Maybe what you want is:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
const char *currency; // pointer
}Rate;
void main(void)
{
Rate rates[1];
rates[0].currency = "one";
printf("%s\n", rates[0].currency);
printf("%p\n", &rates[0].currency);
rates[0].currency = "two";
printf("%s\n", rates[0].currency);
printf("%p\n", &rates[0].currency);
}
As you've seen, a char buffer is an area you can copy characters into. A char pointer does not point to space you can copy characters into unless you allocate that space. So if you want to copy into or modify the actual characters, using a pointer requires some extra work.
But maybe you don't want to copy into or modify the characters. You just want to point to them. That is something a pointer can do and a buffer can't. That is what I did in the above example.
Notice I changed from char* to const char* to remind you and the compiler that using this method you are not allowed to modify the actual characters. You can modify the pointer to point to some other characters elsewhere, but you can't modify the actual characters.
If you want to use a pointer AND you want to copy to or modify the characters, then you need char* as you originally had, not const char* but you also need to manage the allocation and deletion of the buffer space it points to.
In another thread you said
Quote:
Originally Posted by j0hnsmith
C takes a lot more thought compared to PHP and JavaScript
|
Are you sure you want to be learning C now? Maybe you should be learning a simpler subset of C++ instead.
C does not have any kind of strings that act like ordinary objects. That can make things very hard for a beginner writing simple programs. Certainly beginners can learn the things I tried to explain at the beginning of this post. But looking at this thread together with that other thread, I suspect that isn't what you want to do at this point.
C++ has a std:string class which handles strings the way a beginning programmer would expect, very much the way these two threads indicate you expected.
You don't need to learn advanced features of C++ to use it instead of C. C++ works very well if you just pretend it is C with the addition of a few conveniences such as strings and streams. Whether your aim is to learn real C or real C++, that subset of C++ can be a better starting place to learn the basics without getting confused by the difficulties of char* and scanf and other beginner vicious aspects of C.