经过串在C STRUCT [复制]

问题描述 投票:-1回答:4

我用C初学者,需要在结构节能字符串帮助。

(我试过多种方法有它这样做,但程序什么也不打印或我得到(0000005)或程序关闭。(我尝试使用指针作为参数,但效果是一样的,或者使用直scanf函数为text.line和等) 。q;我得到了感觉,我仍然不完全理解指针的想法,这就是问题 - 如果有人解释我应该只是怎么做,我会很高兴。

typedef struct label{
    char *line;
}label;

void save_line(label text){

  printf("Write your name\n");
  char *helper=malloc(30 * sizeof *helper);

  scanf("%s", helper);
  strcpy(text.line, helper);


}

void main(){
   label text;
   save_line(text);
   printf("%s", text.line);

}
c pointers struct
4个回答
2
投票

当你用C参数传递给函数它创建一个副本,让你在主有text变量是不一样的,你在save_line有一个。

你需要传递一个指针text到save_line功能,就像这样:

void save_line(label *text) {

  printf("Write your name\n");
  char *helper=malloc(30 * sizeof *helper);

  scanf("%s", helper);
  text->line = helper;

}

而在主:

void main(){
  label text;
  save_line(&text);
  printf("%s", text.line);
}

2
投票

没有空间分配给您的字符串中line,因为它只是一个没有初始化的指针,所以你将不得不保留一些记忆吧。此外,你的功能分配,其没有被释放的内存(和有关helper,你就不需要记忆两种不同bunchs对相同字符串)。

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

const uint8_t MAX_NAME_SIZE = 20;

typedef struct label{
    char *line;
}label;

void save_line(label text){
    printf("Write your name (max len %u chrs):\n",(MAX_NAME_SIZE-1));
    scanf("%s", text.line);
}

void main(){
    label text;
    text.line = malloc(MAX_NAME_SIZE);
    save_line(text);
    printf("%s", text.line);
    free(text.line);
}

我更愿意分配和在同一范围内释放内存,以避免内存泄漏(同样的功能里面,主要的,里面等),所以为了保持你的结构,为内存在main被管理的例子。你应该考虑一下你的设计,并分析label text;应有的范围。


1
投票

你的代码是错误的,在许多层面:

你可能想是这样的:

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

typedef struct label {
  char *line;
}label;

void save_line(label *text) {   // use label *ttext instead of label text
  printf("Write your name\n");
  text->line = malloc(30 * sizeof *text->line);   // no need for strcpy here anyway 
  scanf("%s", text->line);
}

int main() {               // main should return int *
  label text;
  save_line(&text);        // pass the pointer to text, not just text
  printf("%s", text.line);
  free(text.line);         // free allocated memory
}

还有改进的余地,虽然,例如scanf("%s"), ...是危险的,因为如果用户键入的字符太多,你会得到一个缓冲区溢出。

*阅读:What should main() return in C and C++?


0
投票

strcpy只复制的东西指向源到目的地。对于被复制的东西,它不会在目标分配空间。

如果你的平台有strdup您可以使用,而不是:

text.line = strdup(helper);

如果没有,你之前在分配一些text.line空间strcpy

text.line = malloc(strlen(helper) + 1); // +1 for the null byte at the end
 strcpy(text.line, helper);
© www.soinside.com 2019 - 2024. All rights reserved.