如何在C中的for循环中分配变量?

时间:2019-03-23 16:14:34

标签: c for-loop variable-assignment

Noob,正在处理一个加密问题,我想遍历C语言数组中的组合,即aaa,aab,aac,aba等,然后将每个组合传递给一个函数(以检查该组合是否为正确的代码)。

我可以打印我想要控制的东西,即aa,ab,ba,bb,但不能将这些值放入我的临时变量中。

server=localhost;uid=User;pwd=Password;database=Database;

当我应该获取aa,ab,ba,bb(带有上面的代码)时,我得到了ab,ab,b,b,并且不知道为什么或如何更正它,否则将找到答案,因此是我的Noobish问题。

4 个答案:

答案 0 :(得分:2)

即使它是非常错误的,它看起来也经过了仔细的编码,以创建零警告,其中包含各种类型的字符串数组以及指向周围的字符的指针。

您想要一个由2个字符组成的单个字符串,因为3个字符的数组就足够了:

char temp[3];
temp[2] = '\0'; 

...
    temp[0] = word[i];
    temp[1] = word[j];

    puts(temp); // less typing but essentially the same as printf("%s\n", temp);

答案 1 :(得分:2)

我建议原始海报发布者查看Kernighan and Ritchie的第5章。

/* main.c - This is a novice program. */
/* Copyright (C) 2019 Robin Miyagi https://www.linuxprogramming.ca/
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <error.h>

/*
 * Declared global so that the linker can find it.....................
 */
int main (void);

/*
 * Implementation.....................................................
 */
int
main
(void)
{
  char temp[3];
  int i;
  int j;

  temp[2] = '\0';
  for (i = 0; i < 2; ++i)
    for (j = 0; j < 2; j++)
      {
        temp[0] = 'a' + i;
        temp[1] = 'a' + j;
        printf ("%s\n", temp);  /* temp ---> beginning of array of char. */
      }
  return EXIT_SUCCESS;
}

答案 2 :(得分:0)

temp是指向char的指针。我不知道为什么您的代码是这样构造的,所以我只是假设有一个原因。

            // printf("%c", word[i]);
            // printf("%c\n", word[j]);

是的,这些行不起作用。有点错误。轻松解决:

            printf("%c", temp[i][0]);
            printf("%c\n", temp[j][0]);

我们必须再次取消引用char*才能返回到char。我本可以写*(temp[i]),但是temp[i][0]更容易阅读。

答案 3 :(得分:0)

有了以上帮助,我得以使我的代码按如下方式工作:

#include <stdio.h>
#include <string.h>

int main(void) {

    char * word = "abc";

    char temp[3];
    temp[2] = '\0';

    for (int i = 0; i < strlen(word); i++){
        for (int j = 0; j < strlen(word); j++){
            temp[0] = word[i];
            temp[1] = word[j];
            puts(temp);
        }
    }
    printf("%s", temp);

    return 0;
}

//显示aa,ab,ac,ba,bb,bc,ca,cb,cc,cc(重复)