如何在c中将多个元素插入到数组中

时间:2016-04-10 16:56:56

标签: c arrays elements

该程序假设打印一个16乘16的网格,并在网格中随机水平插入多个元素,当我尝试在网格中插入单个元素时,它工作正常但是当我尝试多个时,它会将符号插入网格中。我想现在为什么会这样。到目前为止,这是我的代码的副本:

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

char **create2DArray(); 
#define WIDTH 16
#define HEIGHT 16
char** myArray; //global array

void main()
 {
   myArray = create2DArray();
 }

char **create2DArray(){
int i,j;
char **array = (char **) malloc(sizeof(char *) * WIDTH);

for(i=0; i<WIDTH; i++)
array[i] = (char *) malloc(sizeof(char) * HEIGHT);


void insertHorizontally(char* word, char** array);
srand(time(NULL));
int WIDTH_1 = (rand()%15)+ 1; 
int HEIGHT_1 = (rand()%15) + 1; 
int insert;

char* word[] = {"CAT","DOG",};

insert = strlen(word);

for(i=0; i<WIDTH; i++){
for(j=0; j<HEIGHT; j++){

array[i][j] = '.';
 }
}

for (j = HEIGHT_1; j < HEIGHT_1 + insert; j ++) {
 array[WIDTH_1][j] = word[j - HEIGHT_1];
}


void printArray(char** array);

for(i=0; i<WIDTH; i++){

for(j=0; j<HEIGHT; j++){

printf("%c ", array[i][j]);
}
printf("\n");
}

return array;
}

任何帮助,提示或建议将不胜感激:)

1 个答案:

答案 0 :(得分:0)

我希望这对你有所帮助。它已在Linux中编译。你应该尝试更可读的来源,以获得良好的帮助。

注意:如果随机函数给出一行中列的最后一个索引,则可能是部分插入了元素。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **create2DArray(); 
#define WIDTH 16
#define HEIGHT 16
char** myArray; //global array


char **create2DArray(){
    int i,j;
    char **array = (char **) malloc(sizeof(char *) * WIDTH);

    for(i=0; i<WIDTH; i++)
        array[i] = (char *) malloc(sizeof(char) * HEIGHT);
    return array;   
}

void insertHorizontally(char** word, int num, char** array)
{
    srand(time(NULL));
    int i, j, k;
    int WIDTH_1; 
    int HEIGHT_1; 
    int insert;

    for(i=0; i<WIDTH; i++){
        for(j=0; j<HEIGHT; j++){
            array[i][j] = '.';
        }
    }
    for(k = 0; k < num; k++){
        insert = strlen(word[k]);
        WIDTH_1 = (rand() % WIDTH); 
        HEIGHT_1 = (rand() % HEIGHT); 
        for (i= 0, j = HEIGHT_1; i < insert && j < HEIGHT  ; j ++, i ++)
            array[WIDTH_1][j] = word[k][j - HEIGHT_1];
    }
}

void printArray(char** array){
    int i, j;
    for(i=0; i<WIDTH; i++){
        for(j=0; j<HEIGHT; j++){
            printf("%c ", array[i][j]);
        }
        printf("\n");
    }
}

void main()
{
    myArray = create2DArray();
    char *word[] = {{"CAT"},{"DOG"},{"FOX"}};
    insertHorizontally(word, sizeof(word)/sizeof(char *), myArray);
    printArray(myArray);

}