Home > Enterprise >  Printing a 2D Array in C
Printing a 2D Array in C

Time:12-17

I'm trying to create a population of 20 those have names (or gens) are generated randomly from a pool.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    srand(time(0));
    // dice KOPYA = int dice = rand() % 101;

    int pop = 20; //Population Number
    int genCount = 5; //Number of gens for 1 person in population

    char a[] = "a";
    char gens[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";
    char target[] = "NuriY";
    char population[pop][genCount];
    char nextPopulation[pop][genCount];

    for(int i=0;i<pop;i  )
    {
        for(int j=0;j<=genCount-1;j  )
        {
            //int dice = rand() % 54;
            //population[i][j] = gens[dice];
            population[i][j] = a[0];
        }
        printf("-. : %s\n",i 1,population[i]);
    }

    return 0;
}

But my result is this I'm not good at 2D arrays. Can you explain me what's my fault?

I can't try anything.

CodePudding user response:

Null terminate the string as I did. https://godbolt.org/z/njqf9s3eG

int main()
{
    srand(time(0));
    // dice KOPYA = int dice = rand() % 101;

    int pop = 20; //Population Number
    int genCount = 5; //Number of gens for 1 person in population

    char a[] = "a";
    char gens[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";
    char target[] = "NuriY";
    char population[pop][genCount];
    char nextPopulation[pop][genCount];

    for(int i=0;i<pop;i  )
    {
        for(int j=0;j<genCount - 1;j  )
        {
            int dice = rand() % 54;
            population[i][j] = gens[dice];
        }
        population[i][genCount - 1] = 0;
        printf("-. : %s\n",i,population[i]);
    }

    return 0;

  • Related