c - 如何让字符串数组的值不变?

标签 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 值,这破坏了我正在尝试基本上填满 ugs 数组的整个想法基于条件。

我该如何解决?所以我在那个 if 条件时刻只是一个 grp->gr_name 的值。

最佳答案

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

测试.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.

关于c - 如何让字符串数组的值不变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54165580/

相关文章:

c - 分配共享内存时出错

c - 级联 hypot() 安全吗?

javascript - Javascript 中数组的最大大小

r - 列是字符而不是因子有什么好的理由吗?

c - #define 在 GCC 中的内联汇编

c - 如何在 eclipse 中重命名(重构)c 宏

javascript - 通过 websocket 发送时,JSON 将 Float32Array 缓冲区大小增加了很多倍

arrays - Angularjs ng-repeat 数组 - 重复值

string - 如何捕获括号之间的字符串?

java - 字符串按点分割 - Java