【问题标题】:Structure arrays with pointer带指针的结构体数组
【发布时间】:2018-12-10 16:36:41
【问题描述】:

我正在学习 C。我编写了代码并且错误是“传递 'strcpy' 的参数 1 使指针从整数而不进行强制转换”。

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

typedef struct humans{
    sname[20];
}human;


int main(){
    human *person=(human *)malloc(sizeof(human)*1);

    int i,k,z;
    for(i=0;i<5;i++){
        person=(human *)realloc(person,sizeof(human)*(i+1));
        strcpy(*person[i].sname , "john");
    }


    for(i=0;i<5;i++){
    printf("%s",*person[i].sname);
    }
    return 0;
}

我想使用 malloc/realloc。

【问题讨论】:

  • #include &lt;stdlib.h&gt; 在代码的开头。
  • 您继续重新分配一行,但访问超出分配的行。新大小是新的 total 大小,而不是要添加的数量。
  • @JonathanLeffler 已修复(已编辑)并已编译但屏幕为空
  • Person 已经是一个指针,所以你正试图 strcpy 一个指向指针的指针。尝试使用 strcpy(person[i].sname , "John");并打印 printf("%s",person[i].sname);
  • @TJGreen 谢谢!它的工作:)

标签: c


【解决方案1】:

如果你有*person[i].sname,你需要person[i].sname。当您将 * 放在它之前时,您会强制数组衰减到指向其第一个元素的指针,当取消引用时,它会为您提供第一个元素的值。

还有:

    person=(human *)realloc(person,sizeof(human)*1);

这个1 应该是i + 1

【讨论】:

  • 我写了 person=(human *)realloc(person,sizeof(human)*(i+1));它编译但屏幕是空的。
【解决方案2】:

我修复了您程序中的直接问题。 不过,这里更深的一点是如何到达您想要的指针。

array[4] 获取第 4 个元素的值。 array 获取指向第一个元素的指针 &amp;array[4] 获取指向第 4 个元素的指针 array + 4 获取指向第 4 个元素的指针 *(array + 4) 获取第 4 个元素的值 *array[4] 获取值,将其视为指针并尝试从指针目标中获取值 - 这需要额外的摆弄才能让编译器相信那将是什么类型。在大多数情况下,这可能毫无意义。

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

typedef struct humans {
    char sname[20];
}human;


void MyStrCpy(char * dst, int dst_n, char * src, int src_n)
{
    for (int n = 0; n < dst_n && n < src_n; ++n)
    {
        dst[n] = src[n];
        if (src[n] == 0) break;
    }
    dst[dst_n] = 0;
}


int main() {
    human *person = (human *)malloc(sizeof(human) * 1);

    int i, k, z;
    for (i = 0; i<5; i++) {
        person = (human *)realloc(person, sizeof(human)*(i + 1));
        //I replace strcpy so it compiles on my machine
        MyStrCpy(person[i].sname, 20, "john", 5);
        person[i].sname[20] = 0;
    }

    for (i = 0; i<5; i++) {
        printf("%s\n", person[i].sname);
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 2019-04-24
    • 2013-02-16
    • 1970-01-01
    • 2017-06-03
    相关资源
    最近更新 更多