just started programming in C a few days ago and I have a quick question for some clarification on a method I found here on Stack that helped me solve a problem. So we have to grab the last three letters of two ID's both of which belong to a student struct. The solution I went with was creating a char sub1[4] and char sub2[4] and then doing a strncpy(sub1, &student1.id[student1.len - 3], 3) for sub1 and sub2. I am not entirely sure what the ampersand is doing here so if anyone can clarify that would be fantastic. My other option was to create a pointer char to each ID and increment it to start at the last 3 and essentially do the same thing I did before. Using the & saves me doing the pointer arithmetic so naturally I prefer to leave it as such, but I'd like to know exactly why it works. Thanks in advance!
Asked
Active
Viewed 50 times
0
-
1`&` means "address of". It returns a pointer to its argument object. So in this case it returns a pointer to the part of the string starting at the `len-3` index. – Barmar Mar 26 '21 at 02:08
-
1Related (not precisely dupe, and it's a more complex case): [Find the address of an index in an array in C](https://stackoverflow.com/q/26899847/364696). Also related [What's the difference between * and & in C?](https://stackoverflow.com/q/28778625/364696), and [What is “&” in “scanf(”%f“, &variableName);” in C programming?](https://stackoverflow.com/q/33930147/364696). – ShadowRanger Mar 26 '21 at 02:15
-
Side-note: "Saves you doing pointer arithmetic" is a weird way to describe this. `&student1.id[student1.len - 3]` is not that much nicer than the pointer arithmetic equivalent, `student1.id + (student1.len - 3)`. And both compile to identical code 99% of the time (there are exceptions where I've seen compilers do clever things when you make it clear you're indexing an array, but it's rare, and almost certainly wouldn't apply in this case). – ShadowRanger Mar 26 '21 at 02:23
-
If the student ID whose suffix you want isn't going to change or be deleted, you don't actually need a copy. You can just create `const char* sub1 = &student1.id[student1.len - 3];`. If it seems like that fits your use case, spend a few minutes thinking about it; that will probably give you a better handle on C "strings". – rici Mar 26 '21 at 02:24
-
1Kind of irrelevant but important, `strncpy()` has corner cases where the string is not terminated, and it looks like your example might be falling victim to it. If you can use `strlcpy()` instead, do that, otherwise make sure `sub1[sizeof(sub1)-1]` is manually set to `'\0'`. – John Bayko Mar 26 '21 at 02:30
-
`... grab the last three letters of two ID's both of which belong to a student struct. ...` Show us the struct. – wildplasser Mar 26 '21 at 02:33