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

时间:2016-01-31 07:57:07

标签: c arrays

如果我想访问存储在n个字符数组指针上的字符串并将该字符串分配给另一个变量,我该怎么做?我在这里:

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]

2 个答案:

答案 0 :(得分:1)

  

循环遍历字符串的每个字符

你已经有了一个指向字符串的指针,现在就像你为指针数组循环一样,你也可以为元素做。

例如,

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]将允许您访问数组中的每个元素。

答案 1 :(得分:1)

你并不遥远,知道你为每个字符串保留10个字符允许你在一次调用中分配内存来处理所有输入,通过声明no_wordschar (*words)[11];来代替而不是分配no_words指针,然后为循环中添加到列表中的每个单词分配。 E.g:

# 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

仔细看看,如果您有任何其他问题,请告诉我。