带有指针和char的结构

时间:2015-02-10 16:19:58

标签: c pointers struct char

我的代码使用的是整数值,但是当我尝试添加字符值时,我就有错误。

这是我的代码:

  1 #include <stdio.h>
  2 
  3 struct _pointer{
  4 
  5     int x;
  6     int y;
  7     char Q[200];
  8 
  9 }address,*pointer;
 10 
 11 
 12 main()
 13 {
 14     pointer = &address;  // here we give the pointer the address.
 15     pointer->x = 10;    // here we give the pointer the value to   variable x.
 16     pointer->y = 30;   // here we give the pointer the value to variable y.
 17     (*pointer).Q = "BANGO!";

 18     printf("The x variable is %d\nThe y variable is %d\nTheText\n",pointer->    x,pointer->y,pointer->Q);
 19 
 20 }
 21 

那我的错误在哪里?

由于

5 个答案:

答案 0 :(得分:2)

复制字符串由strcpy(char *dst, const char *src)

完成

像这样复制字符串

strcpy(pointer->Q,"BANGO!");

答案 1 :(得分:2)

您已将pointer->Q传递给printf,但格式字符串中没有%s

此外,您还应该使用strcpy(pointer->Q, "mystring");

复制字符串

答案 2 :(得分:1)

我可以看到一些错误,最重要的一个是你不能在c中分配数组,把数组的内容设置为你需要复制内容的那些字符串,你可以使用strcpy()为此,在您的情况下,您需要

 strcpy((*pointer).Q, "BANGO!");

另外,你的其余代码似乎不是一个好主意,我推荐这个

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

struct MyStruct
{
    int x;
    int y;
    char Q[200]; 
};

int
main()
{
    struct MyStruct  instance;
    struct MyStruct *pointer;

    pointer = &instance;

    pointer->x = 10;    // here we give the pointer the value to   variable x.
    pointer->y = 30;   // here we give the pointer the value to variable y.

    /* copy the contents of "BANGO!" into the array Q */
    strcpy(pointer->Q, "BANGO!");

    printf("x = %d\ny = %d\nQ = %s\n", pointer->x, pointer->y, pointer->Q);
    /*                           ^ you need this for ---------------^ this */

    /* or even */
    printf("x = %d\ny = %d\nQ = %s\n", instance.x, instance.y, instance.Q);
    /* which will print the same, since you modified it through the pointer */
    return 0;
}

您还应注意,main()会返回int

在一般情况下没有充分理由使用全局变量,有些情况下需要有用,但一般情况下应避免使用它们。< / p>

答案 3 :(得分:1)

在我看来,你甚至没有尝试编译代码。

首先,您不能只为char[]分配一个字符串,而需要使用strcpy(char *to, char *from);

然后,您有printf的三个参数,但只有两个格式%

正确的方式:

 printf("The x variable is %d\nThe y variable is %d\nTheText variable is %s\n",pointer->x,pointer->y,pointer->Q);

strcpy(pointer->Q,"Your text");

答案 4 :(得分:0)

我建议使用

strlcpy(pointer->Q,"BANGO!",sizeof(pointer->Q));

不易出错,并保证字符串无效终止。

相关问题