Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,970 questions

51,912 answers

573 users

How to search a 2d array using two pointers to the first and last elements in the array with C

2 Answers

0 votes
#include <stdio.h>
#include <stdbool.h>
 
#define ROWS 3
#define COLS 4
 
bool searchMatrix(int matrix[][COLS], int *first, int *last, int target) {
    while (first < last & *first != target) {
        first++;
    }
    
    if (*first == target) {
        return true;
    }
 
    return false; // Target not found
}

int main() {
    // Define a 2D array (matrix)
    int matrix[ROWS][COLS] = {
        { 1,  4,  6,  9},
        {11, 17, 18, 29},
        {32, 38, 40, 70}
    };
    
    int target = 29;

    // Pointer to the first element of the matrix
    int *first = &matrix[0][0];

    // Pointer to the last element of the matrix
    int *last = &matrix[ROWS - 1][COLS - 1]; 
    
    if (searchMatrix(matrix, first, last, target)) {
        printf("Target %d found in the matrix.\n", target);
    } else {
        printf("Target %d not found in the matrix.\n", target);
    }

    return 0;
}


/*
run:

Target 29 found in the matrix.

*/

 



answered Sep 22, 2025 by avibootz
0 votes
#include <stdio.h>
#include <stdbool.h>
 
#define ROWS 3
#define COLS 4
 
bool searchMatrix(int matrix[][COLS], int rows, int cols, int target) {
    // Pointer to the first element of the matrix
    int *first = &matrix[0][0];

    // Pointer to the last element of the matrix
    int *last = &matrix[rows - 1][cols - 1]; 

    while (first < last & *first != target) {
        first++;
    }
    
    if (*first == target) {
        return true;
    }
 
    return false; // Target not found
}

int main() {
    // Define a 2D array (matrix)
    int matrix[ROWS][COLS] = {
        { 1,  4,  6,  9},
        {11, 17, 18, 29},
        {32, 38, 40, 70}
    };
    
    int target = 29;

    if (searchMatrix(matrix, ROWS, COLS, target)) {
        printf("Target %d found in the matrix.\n", target);
    } else {
        printf("Target %d not found in the matrix.\n", target);
    }

    return 0;
}


/*
run:

Target 29 found in the matrix.

*/

 



answered Sep 22, 2025 by avibootz
...