C language: returns the first pointer of the same element in two arrays (I used the loop and goto loop labels), gotoloop
//
// Main. c
// Pointer_search
//
// Created by ma c on 15/8/2.
// Copyright (c) 2015 bjsxt. All rights reserved.
// Requirement: Compare the elements in two ordered arrays by searching the pointer and output the first identical element value in the two arrays.
# Include <stdio. h>
Int * searchSameElement (int * a, int * B, int len1, int len2 );
Int main (int argc, const char * argv [])
{
Int a [] = {5, 11, 8, 6, 7, 10 };
Int B [] = {80, 9, 14,8, 14,19, 4 };
// The following method for calculating the length of an array is more common in the internal implementation of the function. However, if you pass it as a parameter to an external function, the array name degrades to a pointer, the following method does not apply to calculating the array length.
Int len1 = sizeof (a)/sizeof (a [0]); // calculate the length of array
Int len2 = sizeof (B)/sizeof (B [0]); // calculate the length of array B
Int * pt = searchSameElement (a, B, len1, len2); // returns the first address of the same value.
If (pt)
Printf ("% d \ n", * pt );
Else
Printf ("the same number don not find! \ N ");
Return 0;
}
Int * searchSameElement (int * a, int * B, int len1, int len2)
{
Int * temp = a; // initialize a temporary pointer to prevent temp from becoming a wild pointer.
For (int I = 0; I <len1; I ++)
{
For (int j = 0; j <len2; j ++)
{
If (* (a + I) = * (B + j ))
{
Temp = a + I;
Goto loop;
// This indicates that the first identical element is found, and the return a + I
}
If (j = len2)
{
Break; // indicates that the first number of external loops is not found in the internal loop.
}
}
If (I = (len1-1 ))
{
Temp = 0;
Goto loop;
// This indicates that the internal and external loops do not find the first same element, jump to the end, return 0
}
}
Loop: return temp;
}