int a[10];
int b[10];
memcmp(a, b, sizeof(int) * 10);
memcmp() only tells us which memory block is bigger/smaller since it just returns -1,0,+1.
Is there a way to know number of matching elements in a[] and b[] just after which the mismatch occurs.
Ex: a = {1, 2, 3, 4, 5, 6}
b = {1, 2, 4}
Here memcmp(a, b, sizeof(int)* 3) would return -1. I want to get 2 as answer
Is there a way we can get number of matching elements with help of memcmp or some similar inbuilt function
I assume you want a low level answer since you must have already rejected the easy way with a loop.
You could XOR the memory block a[0] to a[9] with b[0] to b[9]. The resulting memory will be a block of zeros if, and only if, the original arrays were equal. To get the number of matching elements, count the number of int blocks that have all zero bits.
You could do this blisteringly fast in assembler as the operations are so simple.
A for loop over the two arrays should suffice:
int a[10];
int b[10];
int aLen = sizeof(a)/sizeof(int); /* we can do this since arrays are declared on the stack */
int bLen = sizeof(b)/sizeof(int);
int currentContig = 0;
int maxContig = 0;
for (int aIdx = 0, int bIdx = 0; (aIdx < aLen) && (bIdx < bLen); ) {
if (a[aIdx] == b[bIdx]) {
currentContig++;
aIdx++;
bIdx++;
}
else if (a[aIdx] > b[bIdx]) {
currentContig = 0;
aIdx++;
}
else {
currentContig = 0;
bIdx++;
}
if (currentContig > maxContig) {
maxContig = currentContig;
}
}
fprintf(stdout, "longest contiguous match: %d\n", maxContig);
Please Try Like below
int matched_num=0;
while(a[matched_num]==b[matched_num])
matched_num++;
printf("%d",matched_num);
final printed value will be total number of matched element in both arrays.
Related
This question already has answers here:
Why sizeof(param_array) is the size of pointer?
(8 answers)
Closed 9 months ago.
I am trying to find the smallest missing element of an array using function check, which has two arguments (n and array A). I can't understand why my function check is always returning one and the while loop is never closing.
#include <stdio.h>
bool check(int n, int A[])
{
for (int i = 0; i < sizeof(A); i++)
{
if(A[i] == n)
{
return 1;
}
}
return 0;
}
int main()
{
int A[] = {1, 3, 6, 4, 1, 2};
int n = 1;
while (check(n, A) == 1)
{
n++;
}
printf("%d is missing",n);
}
The compiler adjusts a parameter having an array type to pointer to the array element type.
So this function declaration
bool check(int n, int A[])
is equivalent to
bool check(int n, int *A );
And within the function the expression sizeof(A) is equivalent to the expression sizeof( int * ) and is equal to either 4 or 8 depending on the used system.
Thus this for loop
for (int i = 0; i < sizeof(A); i++)
invokes undefined behavior.
I know but still that's not why the while loop is never stopping.
Answering your above comment it seems that in the used system sizeof( int * ) is equal to 8 and the variable n is placed in memory after the array A as they defined in main
int A[] = {1, 3, 6, 4, 1, 2};
int n = 1;
As a result you get the infinite wile loop because in the for loop within the function the memory occupied by the variable n is checked and n is always equal to itself.
Thus the function always returns 1.
That is in the for loop the array is traversed as it has 8 elements like
int A[] = {1, 3, 6, 4, 1, 2, n, some_indeterminate_value };
#include <stdio.h>
#include <stdlib.h>
int sumArray(int* p);
int main(){
int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, sum;
int* p = array;
sum = printf("The sum of the array is: %d", sumArray(p));
return 0;
}
int sumArray(int* p){
int sum = 0;
while(*p){
sum += *p;
p++;
}
return sum;
}
when i run this code i get a 6-digit value for sum, which looks more like an address. so what exactly am i doing wrong here?
while(*p) is a pretty idiomatic way of processing character strings in C because they have the useful property of being null-terminated. Once the null terminator (character with numeric value of 0) is reached, *p is 0 and the loop ends.
Your array does not have this property so while(*p) is true for the entire length of your array, then it goes out of bounds, which is undefined behavior.
Your options are:
Pass the size along with the array, and use int i = 0; while (i < LENGTH){} or more idiomatically for(int i = 0; i < LENGTH; i++)
Use a designated sentinel value to indicate the end of the array and use while (*p != SENTINEL)
Former option is the least hassle and doesn't require you to designate an arbitrary int as a magic number.
I tried to solve a C coding problem Two Sum in Online coding platform LeetCode
I am not able to return the integer pointer size.
Question:
Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int i,j,sum=0,n1=0,n2=0,sz=1;
int *re;
re = (int*)malloc(sizeof(returnSize));
for(i=0;i<numsSize;i++){
if(sum==target){
break;
}
n1 = i;
for(j=i+1;j<numsSize;j++){
sum = nums[i]+nums[j];
if(sum==target){
n2 = j;
re[0] = n1;
re[1] = n2;
break;
}
}
}
return re;
}
“I expect the output of nums = [2, 7, 11, 15], target = 9, to be [0, 1], but the actual output is ]”
The interface of the function is designed to provide a two-part result, the array and its size.
You are not supposed to return the array by overwriting returnSize.
You are supposed to return the size of the returned array by writing it to the int variable referred by the pointer returnSize (and probably check that it is not a NULL pointer).
The array (i.e. the newly malloced pointer) is supposed to be returned via return, which of course you do. But doing that by overwriting return parameter pointer is what indirectly causes a problem here. (A mre would be required to trace the observed problem to this.)
By the way, I spotted this simply by seeing that you ignore and overwrite one of the parameters, the pointer. If that were correct, then the interface of the function would be inefficient. That can be the case, but usually not for challenges.
I can not reproduce the problem for the provided array. But in any case the function is incorrect..
Instead of this statement (where the argument of the malloc call does not make sense)
re = (int*)malloc(sizeof(returnSize));
^^^^^^^^^^^
there should be
re = (int*)malloc(sizeof( sizeof( int ) * *returnSize ));
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Though the parameter returnSize is redundant because the array according to your description has a fixed size equal to 2.
Moreover there is an unused variable sz=1
The function can invoke undefined behavior because in the case when the target is equal to 0 then the dynamically allocated array is not initialized and has indeterminate values because there is exit from the loop.
for(i=0;i<numsSize;i++){
if(sum==target){
break;
}
// ...
There is no need to dynamically allocate an array. You could return a structure of two elements.
The first parameter should be declared with the qualifier const.
The function can be written simpler and more clear and readable.
#include <stdio.h>
struct PairIndices
{
size_t first;
size_t second;
};
struct PairIndices twoSum( const int *a, size_t n, int target )
{
struct PairIndices pair = { n, n };
for ( size_t i = 0; i < n && pair.first == n ; i++ )
{
size_t j = 1;
while ( j < n && a[i] + a[j] != target ) j++;
if ( j != n )
{
pair.first = i;
pair.second = j;
}
}
return pair;
}
int main(void)
{
int a[] = { 2, 7, 11, 15 };
const size_t N = sizeof( a ) / sizeof( *a );
int target = 9;
struct PairIndices pair = twoSum( a, N, target );
if ( pair.first != N )
{
printf( "a[%zu] + a[%zu] == %d\n", pair.first, pair.second, target );
}
else
{
printf( "There are no two elements in the array "
"sum of which is equal to %d\n", target );
}
return 0;
}
The program output is
a[0] + a[1] == 9
I need to find the length of an array, how would I do this without using the sizeof function.
eg if
Array 1 = [0 1 2 3 4 5 6]
the size of this array would be 7.
If you can't use sizeof (tell us why, please), you can use a loop and a sentinel (-1 or some number that can not be used in the array):
int arr[] = {0, 1, 2, 3, 4, 5, 6, -1};
int count = 0;
while (arr[count] != -1) count++;
Many high-level programming language save the length of an array once it is created.
/* e.g. Java */
int[] foo = new int[10];
assert(foo.length == 10);
But the length of an array is not saved in C! This is useful as you can decide how you want to save the length with respect to optimization. You basically have three possibilities to get/save the length:
mark the end of the array with a certain value (i.e. \0 is used for strings)
char foo[] = "bar";
/* foo has length 4(sic!) as '\0' is automatically added to the end*/
int i = 0;
while(foo[i] != '\0'){
printf("%c",foo[i]);
i++;
}
save the length of the array in a variable
int foo[] = {1,2,3,4};
int length = 4;
for(int i = 0; i < length;i++){
printf("%i, ",foo[i]);
}
use sizeof (warning: sizeof is (mostly) computed at compile time and its use is restricted. you can only use sizeof within the function where the array has been created. when you pass an array to a function you only pass the pointer to the first element. therefore you can loop through this array as you know what offset must be used(type of its elements), but you do not know how big it is unless you also passed the length or added a sentinel value)
/* ok */
int foo[] = {1,2,3,4};
for(int i = 0; i < sizeof(foo)/sizeof(int);i++){
printf("%i, ",foo[i]);
}
/* not ok */
void foo(int bar[]);
void foo(int bar[]){
for(int i = 0; i < sizeof(bar)/sizeof(int);i++){
printf("%i, ",bar[i]);
}
}
int main()
{
int arr[] = {1,2,3,4};
foo(arr);
return 0;
}
I'm learning C, and tried writing a function that, given an array of integer, returns the length of the array. Here is my code:
#include <stdio.h>
int length_of_array(int array[])
{
int length = 0;
int i = 0;
while (array[i] != '\0') {
length += 1;
i += 1;
}
return length;
}
int main()
{
int test_array[] = {1, 2, 3, 4, 5};
printf("%d\n", length_of_array(test_array));
return 0;
}
However, when I compile this code and run it, I says that the length of the array passed in is 14. Does anyone know what could be the problem here?
Strings in C are NUL-terminated. Arrays are not (unless you explicitly do it yourself). The size of array is just the size of array: if allocated as a constant, you can find out the size with sizeof operator. If all you have is a plain pointer, you need to remember the size - there is no way in C to get it once you forget it.
#include <stdio.h>
int main() {
int test_array[] = {1, 2, 3, 4, 5};
int *test_ptr = test_array;
printf("%lu\n", sizeof(test_array) / sizeof(*test_array)); // correct
printf("%lu\n", sizeof(test_ptr) / sizeof(*test_ptr)); // incorrect
return 0;
}