How do you iterate over an array of character arrays in c?

Do you need to manually loop through the array once and get the strlen count of each character array, sum it up, assign it to the destination with the total value and then iterate over the array again?

How do you find the size of an array that contains arrays of characters so you can iterate over them?

+5
source share
4 answers

How do you find the size of an array that contains arrays of characters so you can iterate over them?

There are two ways:

  • Record the number of rows in the array when it is distributed in the variable.
  • Select the extra char*at the end of the array and store the null pointer in it as a sentinel element, similar to the way the NUL character is used to end a line.

, , C . ,

size_t sum_of_lengths(char const **a)
{
    size_t i, total;
    for (i = total = 0; a[i] != NULL; i++)
        total += strlen(a[i]);
    return total;
 }

'\0' .

+7

, , .

:

  • 2 , , , ,

  • 1 . . , . , realloc(). .

+1

, . , . , , .

, realloc, .

: ( char *s[] int n)

int i,l=1;
for (i=0;i<n;i++) l+=strlen(s[i]);
char *r=malloc(l);
r[0]=0;
for (i=0;i<n;i++) strcat(r,s[i]);

: , strcat , . ( - , .) :

int i,l=1;
for (i=0;i<n;i++) l+=strlen(s[i]);
char *r=malloc(l);
char *d=r;
for (i=0;i<n;i++) {
 srtcpy(d,s[i]);
 d+=strlen(s[i]);
}
0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *nstrdup(char **args);
int main (int argc, char **argv)
{
char * this;

this = nstrdup(argv+1);
printf("[%s]\n", this );

return 0;
}

char *nstrdup(char **args)
{
size_t len, pos;
char **pp, *result;

len = 0;
for (pp = args; *pp; pp++) {
        len += strlen (*pp);
        }
result = malloc (1+len);

pos = 0;
for (pp = args; *pp; pp++) {
        len = strlen (*pp);
        memcpy(result+pos, *pp, len);
        pos += len;
        }
result[pos] = 0;
return result;
}
0

All Articles