繁体   English   中英

在C中访问字符指针数组的内容

[英]Access contents of an array of character pointers in C

如果要访问存储在字符指针数组中的字符串并将该字符串分配给另一个变量,该怎么办? 这是我所拥有的:

printf("Number of words in the list: ");
scanf("%d", &no_words);
char *words[no_words];

for (int i = 0; i < no_words; ++i)
{
    words[i] = (char *)malloc((10 + 1)*sizeof(char));
    printf("Word #%d:\n", i +1);
    scanf("%s", words[i]);
    printf("%s", words[i]);         
}

我可以打印从用户输入中获得的字符串,但是我想执行以下类似的操作来遍历字符串的每个字符。

char[11] test= words[i]

遍历字符串的每个字符

您已经有一个指向字符串的指针,现在就像为指针数组循环一样,也可以为元素执行操作。

例如,

for (int i = 0; i < no_words; ++i)
    {
        words[i] = malloc(10 + 1);  //sizeof(char) ==1 in C
                                   // Also, why not check for malloc() success?
        printf("Word #%d:\n", i +1);
        scanf("%10s", words[i]);     //making safe from buffer overflow
        printf("%s", words[i]);     
        int len = strlen(words[i]);

             for (int cnt = 0; cnt < len; cnt++)
             {
                  printf("%c\t", words[i][cnt]);
             }
               printf("\n");
    }

在这里, words[i][cnt]将使您可以访问数组中的每个单独元素。

距离您不远,您知道每个字符串可保留10字符,这样您就可以通过声明no_words char (*words)[11];来在一次调用中分配内存以处理所有输入char (*words)[11]; 而不是分配no_words指针,然后为循环中添加到列表中的每个单词分配。 例如:

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

enum { MAXC = 10 };

int main (void)
{
    char (*words)[MAXC+1] = {NULL};
    char test[MAXC+1] = {0};
    int i, no_words;

    printf ("Number of words in the list: ");
    scanf ("%9d%*c", &no_words);

    if (!(words = calloc (no_words, sizeof *words))) {
        fprintf (stderr, "error: virtual memory exhausted.\n");
        return 0;
    }

    for (i = 0; i < no_words; i++) {
        printf (" enter word[%d]: ", i+1);
        scanf ("%9[^\n]%*c", words[i]);
    }

    printf ("\nWords colected in the list:\n\n");
    for (i = 0; i < no_words; i++)
        printf ("  word[%d] : %s\n", i, words[i]);

    strcpy (test, words[no_words > 1 ? no_words - 2 : 0]);
    printf ("\n test : %s\n\n", test);

    free (words);

    return 0;
}

示例/用途

$ ./bin/scanf_words
Number of words in the list: 9
 enter word[1]: the
 enter word[2]: quick
 enter word[3]: brown
 enter word[4]: fox
 enter word[5]: jumps
 enter word[6]: over
 enter word[7]: a
 enter word[8]: lazy
 enter word[9]: dog

Words colected in the list:

  word[0] : the
  word[1] : quick
  word[2] : brown
  word[3] : fox
  word[4] : jumps
  word[5] : over
  word[6] : a
  word[7] : lazy
  word[8] : dog

 test : lazy

查看一下,如果您还有其他问题,请告诉我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM