Welcome Guest ( Log In | Register )

Outline · [ Standard ] · Linear+

> need help with c programming

views
     
silverhawk
post Nov 23 2021, 10:26 AM

I'm Positively Lustrous
Group Icon
Elite
4,315 posts

Joined: Jan 2003


QUOTE(Grammar Police @ Nov 17 2021, 11:34 PM)
this doesnt work, unless you change

scanf("%i", &n);
n = value
&n = address

Think of it as "scan feed into value n" vs "scan feed into address n". Which do you think is correct?

QUOTE
Is it because char is an array? But shouldnt pointers only be used when there is an array? actually when should you use a pointer?

You will typically use pointers in function parameters to avoid passing the size of the value into the function, using unnecessary memory.

QUOTE
Also if you want to use string in c, you have to do like char *string, so all strings are secretly arrays?

Yes, its the same in almost any language. Strings are really just an array of chars, or maybe even a linked list.

QUOTE
Also why is

char *s = "xyz";
printf("%s", s);

this is OK, but

printf("%s", s[1]);

This is NOT ok

and instead need to put the & like this to work

printf("%s", &s[1]);

??
*
%s is a string, which as you've learnt, is an array of characters, so its expecting a pointer/address. s[1] gives the value, not the address. If you changed %s to %c in printf, s[1] will work.
silverhawk
post Nov 23 2021, 01:32 PM

I'm Positively Lustrous
Group Icon
Elite
4,315 posts

Joined: Jan 2003


QUOTE(Grammar Police @ Nov 23 2021, 11:54 AM)
cannot scan feed into integer and must feed into address? why is it?
*
because the address is where the value is stored. How do you feed into a value?

CODE

int n = 3;

//n = 3;
// &n - 0x0001

// Lets say you input 5
scanf("%d", n);


so if you feed value 5 into 3, does that make sense? Or does it make more sense to say, scan feed (with value 5) into memory address 0x0001.



 

Change to:
| Lo-Fi Version
0.0175sec    0.48    6 queries    GZIP Disabled
Time is now: 24th January 2022 - 09:04 AM