Paulo H
Paulo H

Reputation: 77

How to copy a char array to a line of a table (C)

I have an array of pointers, namely char *nline[MAX_M]. What is the most effective way to copy each nline[i] to the ith-line of a table char TAB[MAX_M][MAX_N]; I've tried

for (i = 0; i < M_max; i++)
    for (j = 0; j < N_max; j++)
        TAB[i][j] = *(nlinha[i] + j);

But it has added garbage to my table.

Upvotes: 0

Views: 342

Answers (2)

rullof
rullof

Reputation: 7424

to copy the ith line from nline use strcpy.

If the size of TAB is different from the size of nline use strncpy to not exceed the size of TAB.

If using strncpy, make sure to add '\0' to each line to make control of the TAB array (The '\0' indicates the end of the string).

strncpy(TAB[i], nline[i], MAX_N);
TAB[i][MAX_N-1] = '\0';

Upvotes: 1

this
this

Reputation: 5290

Use strncpy:

for (i = 0; i < M_max; i++)
    strncpy( TAB[i] , nline[i] , MAX_N  ) ;

Make sure your array of pointers nline has valid pointers.

Upvotes: 2

Related Questions