在c中将一维字符串数组转换为二维字符串数组

时间:2015-03-10 09:58:13

标签: c arrays string malloc

char   *buffer;        /* holds the file contents. */
char   **transfer;
unsigned long    countNewLine = 0;
size_t  rowTrack;
size_t  columnTrack;

// assume countNewLine is 12

buffer_size = BUFSIZ;
buffer = malloc(buffer_size);
transfer = (char**)malloc(sizeof(char*)*sizeof(countNewLine));

columnTrack = 0;


while ( columnTrack < countNewLine ) {

    for ( rowTrack = 0; buffer[rowTrack] != '\n' || buffer[rowTrack] != '\0'; rowTrack++ )
        transfer[columnTrack][rowTrack] = buffer[rowTrack];

        columnTrack++;
}

我试图将1D字符串数组转换为2D。我对自己的错误一无所知。谢谢你的解决方案。

调试器结果:

    buffer  char *  "first\nsecond\nthird\nfourth\nfifth\nsixth\nseventh\n
              eighth\nninth\ntenth\neleventh\ntwelfth\nthirteenth"  0x0000000100801200
    *buffer char    'f' 'f'
    countNewLine    unsigned long   12  12
    transfer    char ** 0x100105520 0x0000000100105520
    *transfer   char *  NULL    0x0000000000000000
    rowTrack    size_t  0   0
    columnTrack size_t  0   0

1 个答案:

答案 0 :(得分:0)

您的代码中存在多个错误。在这一行

transfer = (char**)malloc(sizeof(char*)*sizeof(countNewLine));

第二个sizeof()不正确,该行应为

transfer = malloc(sizeof(char*) * countNewLine);

接下来,您没有为每一行分配内存,这可能是这样的

for ( rowTrack = 0; rowTrack < countNewLine; rowTrack++)
    transfer[rowTrack] = malloc(BUFSIZ);    // or whatever the line length is

for循环永远不会使用||

终止
for ( rowTrack = 0; buffer[rowTrack] != '\n' || buffer[rowTrack] != '\0'; rowTrack++ )

应该是

for ( rowTrack = 0; buffer[rowTrack] != '\n' && buffer[rowTrack] != '\0'; rowTrack++ )

最后,我认为你在这个陈述中颠倒了你的行和列索引:

transfer[columnTrack][rowTrack] = buffer[rowTrack];

有一种更简洁的方式来分割你的字符串,如下所示:

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

#define BUFSIZ 512

int main(void) { 

    char *buffer;
    char *sptr;
    char **transfer = NULL;
    int rows = 0, row;

    /* ... load the file contents */
    buffer = malloc(BUFSIZ);
    strcpy (buffer, "first\nsecond\nthird\nfourth\nfifth\nsixth\nseventh\neighth\nninth\ntenth\neleventh\ntwelfth\nthirteenth");

    /* split the input */
    sptr = strtok(buffer, "\r\n");
    while (sptr) {
        transfer = realloc(transfer, (rows+1) * sizeof(char*));  // expand string array
        transfer[rows] = malloc(1+strlen(sptr));    // memory for string
        strcpy (transfer[rows], sptr);              // copy the token
        rows++;
        sptr = strtok(NULL, "\r\n");
    }

    /* show array */
    printf ("Showing %d rows\n", rows);
    for (row=0; row<rows; row++) {
        printf ("%s\n", transfer[row]);
        free (transfer[row]);                       // release mem
    }

    free (transfer);                                // release mem
    free (buffer);                                  // release mem
    return 0;
}

节目输出:

Showing 13 rows
first
second
third
fourth
fifth
sixth
seventh
eighth
ninth
tenth
eleventh
twelfth
thirteenth