1

I'm trying to set up a search for names in a code, so I'm doing a 2D array to store the names. however I'm not getting the desired output from doing this...

#include <stdio.h>
#include <string.h>

main ()
{
    char name [4][20], string [20];
    int count; 
    for (count = 0; count <3; count ++)
    {
        printf ("Enter your name \n ");
        scanf ("%s", &string);
        strcpy (name [count], string);
    }
    for (count = 0; count <3; count ++)
    {
        printf ("%s \n \n");
    }
    return 0;
}
1
  • This line printf ("%s \n \n"); tries to exactly print the value of which variable, please? Commented Jan 29, 2016 at 7:08

2 Answers 2

2
#include <stdio.h>

#define N_NAME 4
#define NAME_LENGTH 20

int main ()
{
    char names[N_NAME][NAME_LENGTH];

    // input
    int i; 
    for(i = 0; i<N_NAME ; i++) {
        printf("Enter your name: ");
        scanf("%s", names[i]);
    }

    // output
    for(i = 0; i<N_NAME ; i++) {
        printf("%s\n", names[i]);
    }

    return 0;

}

Please check this. It should be what you're looking for.

Few things to point out in your original code:

  1. There's no need for "string" since you've stored what you need in the 2D char array.
  2. Use "i" instead of count, which is better for writing clean code.
  3. To make the %s in printf work, you have to give corresponding variable (pointer).
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah I literally just noticed I had to variable haha My variables have to be 'meaningful' or Iose marks, thanks for your help!
Also i does not need to be signed. The preferred type to index arrays is the unsigned size_t.
-1

Try this.

#include <stdio.h>
#include <string.h>

main ()
{
    char name [4][20], string [20];
    for (int row = 0; row <4; row ++)
    {
        printf ("%s \n \n");
        for (int col = 0; col <20; col ++)
        {
           printf ("Enter your name \n ");
           scanf ("%s", &string);
           strcpy (name [row][col], string);
        }
    }
    return 0;
}

1 Comment

Please explain what's the idea behind your modifications. As it stands the code does not seem to do what the OP is trying to achieve.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.