How can I store String value in char array in C?

19,241

This should work for you:

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

int main() {

    char Password[30];
    char User[5][30];
    int i;

    for(i = 0; i < 5; i++) {
        printf("Enter Password");
        scanf("%s", Password);
        strcpy(User[i],Password);
    }

    for(i = 0; i < 5; i++)
        printf("Password %d: %s\n", i+1, User[i]);

    return 0;

}

The second for loop is to show the output and that every thing is stored right!

Share:
19,241
M.G
Author by

M.G

Updated on September 14, 2022

Comments

  • M.G
    M.G almost 2 years

    I have char array to store string values. I wanted to store the value of a string variable into the char array.

    char Password[30];
    char User[2];
    int i;
    
    for(i=0; i<5; i++) {
            printf("Enter Password");
            scanf("%s", Password);
            strcpy(User[i],Password,30);
    }
    

    I wanted to input the values for the array and it should throw a buffer overflow but I couldn't do it. How can I do it?