我如何从c中的struct函数中的结构中读取字符串?

时间:2018-01-05 17:21:47

标签: c string struct crash structure

当我输入字符串名称并输入我的c程序崩溃时。并尝试另一种方法来获取struct的字符串 但程序崩溃了.//

这是我的代码:

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


struct newacc {
long int userid = 0;
char username[50];
unsigned long mojodi = 0;
};

newacc firstacc(newacc r){
char useridsd[50];
system("cls");
printf("Plz Enter Your New Userid: ");
scanf_s("%ld", &r.userid);
printf("Plz Enter Your Username: ");
scanf_s("%s", useridsd);    //in this line program crashes
strcpy_s(r.username,useridsd); 
.
.
.

1 个答案:

答案 0 :(得分:0)

您无法在结构中定义属性的初始值。

结构的定义:

struct newacc {
  long userid;
  char *username;
  unsigned long mojodi;
} newacc;

初始化值:

#include <stdlib.h> // Needed for calloc

struct newacc *acc = calloc(1, sizeof(newacc));
// userid = 0, username = NULL, mojodi = 0
struct newacc acc2 = { 1, "Foo Bar", 2 };
// userid = 1, username "Foo Bar", mojodi = 2

设置结构值:

unsigned userid = 1;
char *username = (char*) malloc(50 * sizeof(char)); // 50 Chars
username = "Foo Bar";
unsigned long mojodi = 2;

// "->" is used because "*acc" (pointer)
acc->userid = userid;
acc->username = username;
acc->mojodi = mojodi;

// "." is used because of "acc2" (direct)
acc2.userid = userid;
acc2.username = username;
acc2.mojodi = mojodi;

获取结构值:

// "->" is used because of "*acc"
printf("User-ID: %ld", acc->userid);   // 1
printf("Username: %s", acc->username); // "Foo Bar"
printf("Mojodi: %lu", acc->mojodi);    // 2

// "." is used because of "acc2"
printf("User-ID: %ld", acc2.userid);     // 1
printf("Username: %s", acc2.username); // "Foo Bar"
printf("Mojodi: %lu", acc2.mojodi);  // 2