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.