What does the & in front of a string name means

Well, my instructor just gave me a sample function to determine if a char string contains a substring. Here it is:

1
2
3
4
5
6
7
8
9
  bool IsInString(char s1[],char s2[])
{
	for(int i=0;i<strlen(s1);++i)
	{
		if(strncmp(&s1[i],s2,strlen(s2))==0)
			return true;
	}
	return false;
}


One thing I don't understand is, what does the "&" in front of s1 in the strncmp means. Does it mean to check the string from index i or something? Can someone please explain it more clearly for me.
Thank you for help
In C++, the ampersand symbol & has three possible meanings depending on the context:
1) Reference declaration/parameter.
2) Address-of operator. (This is what you have now).
3) Bitwise And operator.

The address-of operator, also known as reference operator, takes the memory address of something.

If we look at the declaration of std::strncmp() we see that the first parameter is a pointer to char.
int strncmp ( const char * str1, const char * str2, size_t num );

http://www.cplusplus.com/reference/cstring/strncmp/

A pointer is a variable containing a memory address.
However, by passing simply s1[i] we would pass a char, and not a pointer to char.
So we prefix it with an ampersand to take its memory address: &s1[i].

To reiterate, s1[i] is the character at position (index) i in string s1.
While &s1[i] is the memory address of the character at position (index) i in string s1.
Last edited on
Topic archived. No new replies allowed.