[英]C: Can not access the struct data in main after enter data from function
I am new to the C program, I am using a struct with array variables to contain my data set.我是 C 程序的新手,我正在使用带有数组变量的结构来包含我的数据集。 However, after I enter one set of data to the struct and want to print the data set out on the main function it shows me something unknown word or empty.SO, how can I get access to the data in the main or in other functions from the struct?
但是,在我向结构体输入一组数据并想要打印主 function 上设置的数据后,它显示了一些未知的单词或空的。所以,我如何才能访问主函数或其他函数中的数据从结构? Did I do something wrong?
我做错什么了吗? Here is the code.
这是代码。 Any suggestions on that?
有什么建议吗? Thanks in advance!
提前致谢!
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include<ctype.h>
struct Team{
char tem[40];
char proj[40];
char leader[40];
char mem1[40];
char mem2[40];
char mem3[40];
};
void project_team(struct Team arr[5]){
char str[100];
printf("Enter> ");
scanf("%[^\n]s",str); //%[^\n]s can input string including space
sscanf( str, "%s %s %s %s %s %s",arr[0].tem,arr[0].proj,arr[0].leader,arr[0].mem1,arr[0].mem2,arr[0].mem3); //conver user input string to words and store in struct variable separately
printf("show: %s %s %s %s %s %s \n",arr[0].tem,arr[0].proj,arr[0].leader,arr[0].mem1,arr[0].mem2,arr[0].mem3);
}
int main(int argc, char *argv[]){
struct Team arr[5];
project_team( &arr[5] );
printf("showthis: %s %s %s %s %s %s \n",arr[0].tem,arr[0].proj,arr[0].leader,arr[0].mem1,arr[0].mem2,arr[0].mem3);
return 0;
}
After I Enter:我输入后:
Enter> TeamA ProjectA Amy Kelvin Fanny Jacky
输入> TeamA ProjectA Amy Kelvin Fanny Jacky
It Display:它显示:
showthis: /usr/lib/dyld � �bx�� *
showthis: /usr/lib/dyld �bx� *
What I expect to show:我希望展示的内容:
showthis: TeamA ProjectA Amy Kelvin Fanny Jacky
展示这个:TeamA ProjectA Amy Kelvin Fanny Jacky
In this call:在这个电话中:
project_team( &arr[5] );
you are passing the address of memory after the last element of the array.您在数组的最后一个元素之后传递 memory 的地址。
You need to write:你需要写:
project_team( arr );
In this call of scanf:在这个 scanf 调用中:
scanf("%[^\n]s",str);
remove the character 's'
from the format string:从格式字符串中删除字符
's'
:
scanf(" %[^\n]",str);
It would be even more safer to write:这样写会更安全:
scanf(" %99[^\n]",str);
Pay attention to that the structure has 6 character arrays with 40 characters in each array.注意结构体有6个字符arrays,每个数组40个字符。 It is evident that
6 * 40
much greater than 100
.很明显
6 * 40
远大于100
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.