如何使字符串数组的值不变?

时间:2019-01-13 02:16:42

标签: c arrays string pointers

在我的以下代码中:

 while((grp = getgrent()) != NULL)
        {
                if(belong_to(username,grp->gr_mem) || strcmp(username,grp->gr_name) == 0)
                {
                        ugs[counter] = grp->gr_name;
                        printf("%s",ugs[counter]);
                        counter++;
                        putchar('\n');
                }

        }

while循环退出后,我得到的ugs字符串数组等于grp->gr_name value,这破坏了正在执行的整个想法,即试图根据条件基本上填充ugs数组。

我该如何解决?因此,在条件时刻,我只是将grp->gr_name的值之一。

1 个答案:

答案 0 :(得分:1)

好-这是一个完整的示例,可能对您有所帮助,还有您的other post

test.c:

#include <stdio.h>
#include <stddef.h>
#include <string.h>
#include <sys/types.h>
#include <grp.h>
#include <pwd.h>

char * list_members(char **members, char *buff);

int main()
{
        int n_grentries = 0, n_pwentries = 0;
        struct group *group;
        struct passwd *passwd;
        char buff[80];

        while((group = getgrent()) != NULL) {
            n_grentries++;
            printf("Group name: %s, ID: %d, members: %s\n",
                group->gr_name, group->gr_gid, list_members(group->gr_mem, buff));
        }
        endgrent();

        while((passwd = getpwent()) != NULL) {
            n_pwentries++;
            printf("User name: %s, UID: %d, shell: %s\n",
                passwd->pw_name, passwd->pw_uid, passwd->pw_shell);
        }
        endpwent();

        printf("There are  %d groups and %d users on the system.\n",
            n_grentries, n_pwentries);
        return 0;
}

char * list_members(char **members, char *buff)
{
    buff[0] = '\0';
    while (members && *members) {
        if (*buff)
          strcat (buff, ", ");
        strcat (buff, *members);
        members++;
    }
    return buff;
}

示例输出:

Group name: root, ID: 0, members: paulsm, 
Group name: daemon, ID: 1, members: 
Group name: bin, ID: 2, members:
Group name: adm, ID: 4, members: syslog, paulsm, 
...
User name: root, UID: 0, shell: /bin/bash
User name: daemon, UID: 1, shell: /usr/sbin/nologin
User name: bin, UID: 2, shell: /usr/sbin/nologin
User name: sys, UID: 3, shell: /usr/sbin/nologin
...
There are  72 groups and 45 users on the system.