如何在C中将字符串分配给结构变量?

发布于 2025-01-09 20:20:24 字数 993 浏览 1 评论 0原文

我无法弄清楚如何仅使用 头文件将字符串分配给结构变量。

以下代码给我一个错误,我无法修复它。

#include <stdio.h>
 struct Student
{
    char name[50];
};
int main()
{
   struct Student s1;
   printf("Enter studen's name:\n");
   scanf("%s",s1.name);
   printf("Name : \n",s1.name);
   s1.name={"Hussain"};
   printf("Name : \n",s1.name);
}

编译时出现以下错误:

test.c: In function 'main':
test.c:12:12: error: expected expression before '{' token
    s1.name={"Hussain"};
            ^

我尝试按以下方式初始化它:
s1.name="侯赛因";
但这也行不通。
我可以通过使用指针来避免这种情况,如下所示:

#include <stdio.h>
 struct Student
{
    char *name;
};
int main()
{
   struct Student s1;
   printf("Enter studen's name:\n");
   scanf("%s",s1.name);
   printf("Name : %s\n",s1.name);
   s1.name="Hussain";
   printf("Name : %s\n",s1.name);
}

这段代码工作得很好,没有错误。
但我想知道我到底在数组上做错了什么,这使得我的代码无法工作。

I am unable to figure out how to assign a string to a struct variable using only <stdio.h> header file.

The following code gives me an error and I am unable to fix it.

#include <stdio.h>
 struct Student
{
    char name[50];
};
int main()
{
   struct Student s1;
   printf("Enter studen's name:\n");
   scanf("%s",s1.name);
   printf("Name : \n",s1.name);
   s1.name={"Hussain"};
   printf("Name : \n",s1.name);
}

It gives the following error while compilation:

test.c: In function 'main':
test.c:12:12: error: expected expression before '{' token
    s1.name={"Hussain"};
            ^

I have tried initializing it in the following way:
s1.name="Hussain";
But this doesn't work too.
I could avoid this by the use of pointers as follows:

#include <stdio.h>
 struct Student
{
    char *name;
};
int main()
{
   struct Student s1;
   printf("Enter studen's name:\n");
   scanf("%s",s1.name);
   printf("Name : %s\n",s1.name);
   s1.name="Hussain";
   printf("Name : %s\n",s1.name);
}

This code works perfectly fine with no errors.
But I want to know where exactly I am doing wrong with the array, which is making my code not work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

江心雾 2025-01-16 20:20:24

char 数组(以及一般数组)不能直接赋值,只能初始化。要将字符串写入 char 数组,请使用 strcpy

strcpy(s1.name, "Hussain");

后一个代码(其中 name 成员是指针)适用于赋值,因为指针被分配了字符串常量的起始地址。另请注意,在这种情况下您不能(至少现在不能)使用 strcpy,因为 s1.name 不指向任何地方。您首先需要使用 malloc 分配内存,或者使用 strdup 同时执行这两个步骤。也由于这个原因,在分配内存之前您还不能使用 scanf

如果不允许使用 string.h 中的函数,那么您需要一次将一个字符写入数组,然后在末尾写入一个终止空字节。

A char array (and arrays in general) can't be assigned a value directly, only initialized. To write a string into a char array, use strcpy.

strcpy(s1.name, "Hussain");

The latter code where the name member is a pointer works for the assignment because the pointer is assigned the start address of the start of the string constant. Also note that you can't (at least not yet) use strcpy in that case because s1.name doesn't point anywhere. You would first need to allocate memory using malloc, or perform both steps at once using strdup. Also for this reason, you can't yet use scanf until you allocate memory.

If you're not allowed to use functions from string.h, then you would need to write the characters into the array one at a time, and then write a terminating null byte at the end.

甜妞爱困 2025-01-16 20:20:24

数组没有赋值运算符。所以这些赋值语句

s1.name = { "Hussain" };
s1.name = "Hussain";

是无效的。

您可以使用标准 C 字符串函数 strcpy 将字符串文字的元素复制到数组 s1.name 中,例如

#include <string.h>

//...

strcpy( s1.name, "Hussain" );

如果您可能不使用标准字符串函数,那么您需要编写一个循环,例如

const char *p = "Hussain";

for ( char *t = s1.name; ( *t++ = *p++ ) != '\0'; );

或者

for ( char *t = s1.name, *p = "Hussain"; ( *t++ = *p++ ) != '\0'; );

请注意,您的程序有未定义的行为。指针s1.name未初始化,并且不指向数组类型的有效对象。因此,此代码片段中对 scanf 的调用会调用未定义的行为。

struct Student s1;
printf("Enter studen's name:\n");
scanf("%s",s1.name);

Arrays do not have the assignment operator. So these assignment statements

s1.name = { "Hussain" };
s1.name = "Hussain";

are invalid.

You could use the standard C string function strcpy to copy elements of the string literal to the array s1.name like

#include <string.h>

//...

strcpy( s1.name, "Hussain" );

If you may not use standard string functions then you need to write a loop as for example

const char *p = "Hussain";

for ( char *t = s1.name; ( *t++ = *p++ ) != '\0'; );

Or

for ( char *t = s1.name, *p = "Hussain"; ( *t++ = *p++ ) != '\0'; );

Pay attention to that the second your program has undefined behavior. The pointer s1.name is not initialized and does not point to a valid object of an array type. So the call of scanf in this code snippet invokes undefined behavior.

struct Student s1;
printf("Enter studen's name:\n");
scanf("%s",s1.name);
锦欢 2025-01-16 20:20:24

如果您无法使用 ,则必须实现您自己的 strcpy() 版本:

void copystring(char *dest, const char *src)
{
    const char *p = src;
    while (*p) {
        *dest = *p;
        p++;
        dest++;
    }
    *dest = '\0'; // Null-terminate string (as pointed by @Ted)
}

确保 dest 有足够的空间容纳src

另外,请避免在代码中使用 scanf()。使用 fgets() 作为替代方案。

编辑: 正如 Jabberwocky 所指出的,fgets()\n 在字符串中读取。但由于不允许使用 ,因此您必须实现自己的函数以将其替换为空终止符:

int findchar(const char *str, char c)
{
    int pos;
    for (pos = 0; str[pos]; ++pos)
        if (str[pos] == c)
            return pos;
    
    return -1;
}

您可以像这样使用它:

char str[100];
if (!fgets(str, sizeof str, stdin)) {
    // fgets() failed. Do something.
} else {
    int nwln = findchar(str, '\n');
    if (nwln == -1) {
        // You probably entered more than 100 characters
        // because \n couldn't be found.
    } else {
        str[nwln] = '\0';
    }
}

If you can't use <string.h>, then you have to implement your own version of strcpy():

void copystring(char *dest, const char *src)
{
    const char *p = src;
    while (*p) {
        *dest = *p;
        p++;
        dest++;
    }
    *dest = '\0'; // Null-terminate string (as pointed by @Ted)
}

Make sure that dest has enough space to hold src.

Also, avoid using scanf() in your code. Use fgets() as an alternative.

EDIT: As pointed by Jabberwocky, fgets() leaves \n read in the string. But since using <string.h> is not allowed, you have to implement your own function to replace it with a null-terminator:

int findchar(const char *str, char c)
{
    int pos;
    for (pos = 0; str[pos]; ++pos)
        if (str[pos] == c)
            return pos;
    
    return -1;
}

You can use it like:

char str[100];
if (!fgets(str, sizeof str, stdin)) {
    // fgets() failed. Do something.
} else {
    int nwln = findchar(str, '\n');
    if (nwln == -1) {
        // You probably entered more than 100 characters
        // because \n couldn't be found.
    } else {
        str[nwln] = '\0';
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文