-2
#include <stdio.h>    

void main()
{
    char couples[3][50] = { "Paul Kathy", "John Nora", "Martin Mary" };
    char husbands[3][50];
    char wives[3][50];  
    int i = 0;
    int j = 0;

    puts("Husbands: ");
    for (i = 0; i < 3; i++)
    {
        while (couples[i][j] != ' ')
        {
            couples[i][j] = husbands[i][j];
            j++;
        }
        husbands[i][j] = '\0';
        puts(husbands[i]);
        j = 0;
    }

}

I have created a program similar to this before and it ran perfectly. However while this does build and compile successfully, it doesn't run correctly. Essentially, I'm trying to separate couples into a separate string based up the space character. What am I doing wrong?

Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
John
  • 33
  • 1
  • 7
  • 4
    `main` has two valid signatures: `int main (void)` and `int main (int, char **)`. Any literature teaching you otherwise should be avoided. Seek better learning material and it won't be so hard to get a grasp on the basics of C. – Oka Oct 21 '16 at 19:50
  • "it doesn't run correctly"? What does it do? – Ahmad Khan Oct 21 '16 at 19:57
  • See [What should `main()` return in C and C++](http://stackoverflow.com/questions/204476/) for the full details of what is and is not allowed. The number of platforms where `void main()` is allowed is rather small. – Jonathan Leffler Oct 21 '16 at 20:25

2 Answers2

3

Here's your problem:

couples[i][j] = husbands[i][j];

You are assigning husbands to couples and not the other way around as you need to.

Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
Riley
  • 698
  • 6
  • 11
1

Try something simple. The sscanf() function can extract data from strings rather easily:

#include <stdio.h>

int main(void)
{
    char couples[3][50] = { "Paul Kathy", "John Nora","Martin Mary" };
    char husbands[3][50];
    char wives[3][50];  
    int i = 0;

    for (i = 0; i < 3; i++)
    {
        /* Extract husband and wife names. You know they are separated by a space. */
        sscanf(couples[i], "%s %s", husbands[i], wives[i]);
    }
}

The issues in the original code include:

  1. Couple string was getting over-written by husband string which was not initialized.

  2. Not extracting wife names.

Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
MayurK
  • 1,825
  • 11
  • 24
  • 1
    You should explain what you're doing (and drop the boilerplate comment that shouldn't be in the original question either). You should also explain what's wrong with the original code — why wasn't it workinig. – Jonathan Leffler Oct 21 '16 at 19:58
  • @JonathanLeffler Thank you for the feedback. I have updated my answer. Please review it. – MayurK Oct 21 '16 at 20:23