【问题标题】:Struct with pointer and char in cc中带有指针和字符的结构
【发布时间】:2015-04-10 18:32:21
【问题描述】:

我的代码正在使用整数值,但是当我尝试添加字符值时,出现错误。

这是我的代码:

  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 

那么我的错误在哪里?

谢谢

【问题讨论】:

  • 你想做什么?

标签: c pointers struct char


【解决方案1】:

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

像这样复制字符串

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

【讨论】:

  • C 语言字符串(char * 类型)不支持使用操作符 = 进行复制。
【解决方案2】:

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

你也应该用strcpy(pointer-&gt;Q, "mystring");复制字符串

【讨论】:

    【解决方案3】:

    我可以看到一些错误,最重要的是你不能在c中分配给数组,将数组的内容设置为你需要复制内容的字符串,你可以使用@987654322 @为此,您需要

     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

    在一般情况下没有充分的理由使用全局变量,在某些情况下它们是需要有用,但一般情况下您应该避免使用它们。

    【讨论】:

    • @pythonlover 只是为了说明指针是如何工作的。你know
    【解决方案4】:

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

    首先,您不能只将字符串分配给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");
    

    【讨论】:

    • 是的! ,我认为错误在 (*pointer).Q = "BANGO!"; .
    【解决方案5】:

    我建议使用

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

    这更不容易出错,并保证您的字符串以空值终止。

    【讨论】:

    • strlcpy 不是标准的。
    • @iharob 是的,你是对的,但使用它没有坏处吗?因为它更安全
    • 如果有的话比较安全,因为不是标准,所以不保证。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    • 2016-06-23
    相关资源
    最近更新 更多