Thread: Dealing with arrays

  1. #1
    Registered User
    Join Date
    Dec 2018

    Dealing with arrays


    I have an array of char values which contains module codes.

    char modules[8][8];

    Within this array i have multiple of the same module codes as it is being taken from a file. I need to know how to remove any duplicate values from the array, i assume by iterating over the whole thing to compare each value against each other to check if it's the same? Or is there an easier or more efficient way of doing it?

    I am pretty desperate at this point as I really don't know what i'm doing so any help is appreciated.

  2. #2
    Registered User
    Join Date
    Dec 2017
    "Module codes" is not a standard term so I have no idea what that is. But since you are storing them in a 2D array of char they are most likely either single characters (but then why are they in a 2D array?) or regular C strings (up to seven characters and a final '\0' character).

    Since you didn't specify, I'll just assume the latter. If they aren't sorted then you need to compare each one to all of the ones following it. If they are sorted you just need to compare each to the next one and if it's the same, remove the duplicate and compare again.

    Example of an unsorted list:
    #include <stdio.h>
    #include <string.h>
    int main() {
        char m[8][8] = {
        int size = 7;  // 7 strings in the array
        for (int i = 0; i < size; ++i)
            for (int j = i + 1; j < size; )
                if (strcmp(m[i], m[j]) == 0) {
                    for (int k = j + 1; k < size; ++k)
                        strcpy(m[k - 1], m[k]);
        for (int i = 0; i < size; ++i)
            printf("%s\n", m[i]);
        return 0;
    Ordinary language is totally unsuited for expressing what physics really asserts.
    Only mathematics can say as little as the physicist means to say. - Bertrand Russell

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems dealing with arrays
    By ktmc03 in forum C Programming
    Replies: 8
    Last Post: 11-12-2013, 03:07 PM
  2. dealing with dynamic arrays
    By waqas94 in forum C++ Programming
    Replies: 9
    Last Post: 07-15-2013, 12:01 PM
  3. Dealing With Multi Dim Char Arrays
    By mike_g in forum C Programming
    Replies: 8
    Last Post: 06-15-2007, 01:52 PM
  4. Arrays, and Functions dealing with them
    By Argentum in forum C++ Programming
    Replies: 6
    Last Post: 12-05-2005, 07:25 PM
  5. Dealing with the end of an Array
    By Philandrew in forum C++ Programming
    Replies: 7
    Last Post: 10-23-2004, 07:57 PM

Tags for this Thread