有关char数组的结构问题 [英] question on struct with char array

查看:266
本文介绍了有关char数组的结构问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的代码片段

struct encode
{

   char code[MAX];

}a[10];

int main()
{ 
char x[]={'3','0','2','5','9','3','1'};

  for(i=0;i<1;i++)
  {

      printf("%c",x[i]);

//This will printout like 3025931 now I want this to be stored in structure.         
  }

strcpy(a[0].code,x); 
// or 
a[0].code=x;//neither works

display();

}

void display()
{
printf("%c",a[0].code);
}

我希望输出如下:3025931。

I want the output to be like:3025931.

由于不兼容的分配类型,我没有收到。请告诉我我在哪里错了。

Which I am not getting due to incompatible assign type. Please tell me where am i going wrong.

推荐答案

我在这里看到两个问题。第一个是 strcpy 的源代码是 a ,可能应该是 x

I see two problems here. The first is that the source of the strcpy is a where it probably should be x.

第二个是 x 不是以空终止的。 C中的字符串是以null结尾的字符数组。

The second is that x is not null-terminated. Strings in C are null-terminated character arrays.

我会更改两行:

char x[] = {'3','0','2','5','9','3','1'};
strcpy(a[0].code, a);

to:

char x[] = {'3','0','2','5','9','3','1', '\0'};
strcpy(a[0].code, x);

这是一个完整的程序,给你你想要的(它实际上打印出两次,一次在您的内循环字符,并且一次使用 printf ,以便您可以看到它们相同):

Here's a complete program that gives you what you want (it actually prints out the number twice, once in your inner loop character by character and once with the printf so that you can see they're the same):

#include <stdio.h>
#include <string.h>
#define MAX 100
struct encode {
    char code[MAX];
} a[10];

int main() {
    int i, j;
    char x[] = {'3','0','2','5','9','3','1','\0'};

    for(i = 0; i < 1; i++) {
        for(j = 0; j < 7; j++) {
            printf("%c", x[j]);
        }
        printf("\n");

        strcpy(a[0].code, x);
    }
    printf("%s\n",a[0].code);
    return 0;
}

基于注释更新


我很抱歉我很开心C.对于在开头没有正确粘贴代码段的歉意:printf(%c,a [0] .code);不显示3025931。

I am sorry. I am new to C. My apologies for not pasting the code snippet correctly in the beginning: "printf("%c",a[0].code);" doesn't display "3025931".

不,不会。这是因为 a [0] .code 是一个字符数组(在这种情况下为字符串),您应该使用%s %c。更改 printf 中的格式说明符应该可以解决这个问题。

No, it won't. That's because a[0].code is a character array (string in this case) and you should be using "%s", not "%c". Changing the format specifier in the printf should fix that particular issue.

这篇关于有关char数组的结构问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆