How do I get the rgb values of a pixel from a given surface and x and y coordinates in SDL2?

Hello and welcome to the forum!

You can retrieve the color/value of a specific pixel in an SDL_Surface by using the SDL_GetRGB function, or SDL_GetRGBA if the loaded image has an alpha channel (like in a PNG image for example).
Below I’ve added a code example on how such a function can be created and used.
You might have to convert between small and big endian, depending on your OS etc. So if you have any issues with the incorrect pixel color being returned from the function, small/big endian might be the issue. I’m not very good with that so I sadly can’t help you with it.

Code
SDL_Color GetPixelColor(const SDL_Surface* pSurface, const int X, const int Y)
{
	// Bytes per pixel
	const Uint8 Bpp = pSurface->format->BytesPerPixel;

	/*
	Retrieve the address to a specific pixel
	pSurface->pixels	= an array containing the SDL_Surface' pixels
	pSurface->pitch		= the length of a row of pixels (in bytes)
	X and Y				= the offset on where on the image to retrieve the pixel, (0, 0) is in the upper left corner of the image
	*/
	Uint8* pPixel = (Uint8*)pSurface->pixels + Y * pSurface->pitch + X * Bpp;

	Uint32 PixelData = *(Uint32*)pPixel;

	SDL_Color Color = {0x00, 0x00, 0x00, SDL_ALPHA_OPAQUE};

	// Retrieve the RGB values of the specific pixel
	SDL_GetRGB(PixelData, pSurface->format, &Color.r, &Color.g, &Color.b);

	return Color;
}

int main(int argc, char *argv[])
{
	SDL_Surface* pSurface = IMG_Load("Image.png");

	// Offset (4, 4) in the image/surface
	const SDL_Color Color = GetPixelColor(pSurface, 4, 4);

	if((Color.r == 255) && (Color.g == 0) && (Color.b == 0))
		std::cout << "The pixel is fully red" << std::endl;

	return 0;
}

More information: https://wiki.libsdl.org/SDL_GetRGB and https://wiki.libsdl.org/SDL_GetRGBA