Home > front end >  How to create array of pairs of strings?
How to create array of pairs of strings?

Time:05-22

I'm new to C and I have been trying to create and print an array of pairs of strings for a while now but keep getting errors. Here's what I want the array to look like:

[[str1, str2], [str3, str4], ...]

Here is what I've tried:

...
char str1[51], str2[51];
char *pairs[amount][2][51];
for (int i = 0; i < amount; i  ) {
    scanf("%s %s", str1, str2);
    // assign str at ith index of pairs and 0th/1st index within pair
    *pairs[i][0] = str1;
    *pairs[i][1] = str2;
}
// print pairs in backwards order
for (int i = 0; i < amount; i  ) {
    printf("%s %s", *pairs[i][1], *pairs[i][0]);
}

Input:

1 2
3 4
5 6

Output:

6 5
6 5
6 5

My interpretation of this is to declare a char array of pointers to pairs of strings, each string containing upwards of 50 chars, then assign strings to each pair and print them backwards. Clearly I'm doing something wrong here, but what? It seems like only the last pair is being accessed.

I know I can just print the strings backwards as they're being inputted, but I'm trying to understand arrays and declarations better.

CodePudding user response:

Your problem is:

*pairs[i][0] = str1;

This copies the reference (and not the value) of str1 to pairs[i][0]. If you want to copy the value, You should use strcpy() function in string.h header file. Another solution is the following example:

An example without struct

#include <stdio.h>

int main() {
    char list_of_pairs[3][2][51];
    printf("Enter your pairs:\n");

    for (int i = 0; i < 3; i  ) {
        scanf(" %s %s", list_of_pairs[i][0], list_of_pairs[i][1]);
    }

    for (int i = 0; i < 3; i  ) {
        printf("pair -> first: %s second: %s\n", list_of_pairs[i][0], list_of_pairs[i][1]);
    }

    return 0;
}

CodePudding user response:

Array pointers make sense if you want to dynamically allocate the memory

#define MAXLENGTH 51

char (*addPair(size_t size, char (*array)[2][MAXLENGTH], const char *s1, const char *s2))[2][MAXLENGTH]
{
    array = realloc(array,   size * sizeof(*array));

    if(array)
    {
        strncpy(array[size -1][0], s1, sizeof(array[0][0]));
        strncpy(array[size -1][1], s2, sizeof(array[0][0]));
        array[size -1][0][MAXLENGTH - 1] = 0;
        array[size -1][1][MAXLENGTH - 1] = 0;
    }
    return array;
}
  • Related