0

Question about C

Hi. I started learning C recently and I am not quite used to its basic knowledge. Here are some of my questions: 1. When you create a char variable, how do you decide its size? 2. In what situation do you use pointer and in what situation do you not? I am kind of struggle with the idea of pointer, so if you can explain to me its importance in C, I would be appreciated. BTW if possible, since I have learn Python, the explanation that is equivalent to Python would be nice. Thanks for answering my questions.

13th Jul 2019, 4:59 PM
Harry
Harry - avatar
3 Réponses
+ 4
Hi Harry! You can get the size of any variable using the sizeof function. char x = 'a'; printf("%d", sizeof(x)); All characters have the same size, so you can also use sizeof(char). Pointers point to a memory location, so they can "track" a variable. Let's see two examples: //No pointers int x = 5; int y = x; x = 10; printf("%d", y); //5 //Pointers int x = 5; int* y = &x; x = 10; printf("%d", y); //10 Pointers can also be used to change variable's values in functions
13th Jul 2019, 5:06 PM
Airree
Airree - avatar
0
Airree You need to dereference y before passing to printf();
14th Jul 2019, 2:16 AM
Jared Bird
Jared Bird - avatar
0
Uses for pointers: As Airree said when you need to change the value of variable in a function. If you need to pass an array into a function you cant do this directly, so you pass the address of the array, and the size. If you are using a large structure then you can pass a pointer to the structure to functions (in some cases) instead of the structure its self. This saves an extra copy of the structure being made. Also you need to use pointers if you need to allocated memory dynamically. If you had an array but did not know how big it needs to be until after the program runs then this needs dynamically allocated memory.
14th Jul 2019, 2:34 AM
Jared Bird
Jared Bird - avatar