简体   繁体   English

循环遍历多维数组的第一列

[英]Loop through first column of multidimensional array

I have a multidimensional array containing IP addresses and their corresponding Gateways.我有一个包含 IP 地址及其相应网关的多维数组。 The structure of the array is shown below.数组的结构如下所示。 I'd like to loop through the array and assign the first column of IP addresses to my network interface.我想遍历数组并将 IP 地址的第一列分配给我的网络接口。 I expect the interface to at some point to have several IP Addresses assigned to it.我希望接口在某个时候会分配给它几个 IP 地址。 Later I intend to add a function to ping the gateways.稍后我打算添加一个 function 来 ping 网关。

I can't seem to get the value of just the first column with which to use to execute my command.我似乎无法获得用于执行我的命令的第一列的值。 I'm sure I'm referencing the array incorrectly.我确定我错误地引用了数组。 Here's what I have so far.这是我到目前为止所拥有的。

char eth0IntName[256];

const char *arrayIPAddress[3][2]={
    {"192.168.16.65", "192.168.16.66"},
    {"192.168.17.65", "192.168.17.66"},
    {"192.168.18.65", "192.168.18.66"}};
    
int main(int argc, char *argv[])
{

    char cmdStr[256];
    
    strcpy(eth0IntName, "eth0");
    
    for(int i=0; i<3; i++)
    {
        sprintf(cmdStr, "/sbin/ip addr add %s/30 dev %s", (char *)&arrayIPAddress[i][0], eth0IntName);
        printf("Executing: /sbin/ip addr add %s/30 dev %s", (char *)&arrayIPAddress[i][0], eth0IntName);
    }

    return 0;
    
}

I was overcomplicating it.我把它复杂化了。 My sprintf line was wrong.我的 sprintf 线是错误的。 Also, I needed to actually execute the command.另外,我需要实际执行命令。 I added system(cmdStr);我添加了系统(cmdStr); after that line.在那条线之后。 Here's how the code looks now.这是代码现在的样子。

char eth0IntName[256];

const char *arrayIPAddress[3][2]={
    {"192.168.16.65", "192.168.16.66"},
    {"192.168.17.65", "192.168.17.66"},
    {"192.168.18.65", "192.168.18.66"}};
    
int main(int argc, char *argv[])
{

    char cmdStr[256];
    
    strcpy(eth0IntName, "eth0");
    
    for(int i=0; i<3; i++)
    {
        sprintf(cmdStr, "/sbin/ip addr add %s/30 dev %s", arrayIPAddress[i][0], eth0IntName);
        system(cmdStr);
        printf("Executing: /sbin/ip addr add %s/30 dev %s", arrayIPAddress[i][0], eth0IntName);
    }

    return 0;
    
}

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

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