简体   繁体   English

Malloc和Struct

[英]Malloc and Struct

i am facing some difficulties with malloc and structs. 我在使用malloc和结构时遇到了一些困难。 I want to read the m_data.number_chars as shown in my code (which is an integer) to be the memory that i want to allocate.. But when i compile my code, and run it, it crushes.. Any ideas..? 我想读取代码中的m_data.number_chars(是整数),作为我要分配的内存。但是当我编译代码并运行它时,它会崩溃..有什么想法吗? Thanks in advance! 提前致谢!

#include <stdio.h>

struct movies {
int number_chars;
char name;
int made_year;
float money;
};
struct movies m_data;


int main()
{
   scanf("%d",&m_data.number_chars);
   m_data.name=malloc(m_data.number_chars);
   gets(m_data.name);
   printf("%s",m_data.name);
}

When calling scanf , you need to pass the address of the variable to hold the result (using the ampersand & ). 调用scanf ,您需要传递变量的地址以保存结果(使用& )。 This would definitely cause serious memory problems right there. 这肯定会导致严重的内存问题。

Also, name is of type char . 另外, name的类型为char char is not a pointer. char不是指针。 Therefore, you cannot assign the result of malloc() to name . 因此,您不能将malloc()的结果分配给name

You need a pointer type. 您需要一个指针类型。

Also, "crushes" is not a technical description of what is going wrong. 同样,“暗恋”也不是技术问题的技术描述。 You'll probably get further if you can articulate your situation better. 如果您可以更好地阐明自己的情况,那么您可能会走得更远。

Try: 尝试:

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

struct movies {
int number_chars;
char *name;
int made_year;
float money;
};
struct movies m_data;


int main()
{
   scanf("%d",&m_data.number_chars);
   m_data.name=malloc(m_data.number_chars);
   gets(m_data.name);
   printf("%s",m_data.name);
   free(m_data.name)
}

Well you were supposed to pass char* to the scanf - more specifically address of the variable on which input will be stored. 好吧,您应该将char*传递给scanf更具体地说是将输入存储在其中的变量的地址。 You didn't do that. 你没那么做

No return value check for the standard functions and ofcourse you didn't use malloc earlier. 没有对标准函数进行返回值检查,当然您之前没有使用过malloc

#include <stdio.h>
#include <stdlib.h>
struct movies {
    int number_chars;
    char* name;
    int made_year;
    float money;
};
struct movies m_data;


int main(void)
{
    if( scanf("%d",&m_data.number_chars)!= 1){
        fprintf(stderr, "%s\n", "Error in input");
        exit(EXIT_FAILURE);
    }
    getchar();
    if(m_data.number_chars <= 0){
        fprintf(stderr, "%s\n", "Error in number of character count");
        exit(EXIT_FAILURE);
    }
    m_data.name = malloc(m_data.number_chars+1);
    if(!m_data.name){
        perror("Malloc error");
        exit(EXIT_FAILURE);
    }
    if(fgets(m_data.name,m_data.number_chars+1,stdin)){
        printf("[%s]\n",m_data.name);
    }
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM