Home > Enterprise >  C: Can not access the struct data in main after enter data from function
C: Can not access the struct data in main after enter data from function

Time:04-05

I am new to the C program, I am using a struct with array variables to contain my data set. 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? 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

It Display:

showthis: /usr/lib/dyld � �bx�� *

What I expect to show:

showthis: TeamA ProjectA Amy Kelvin Fanny Jacky

CodePudding user response:

In this call

project_team( &arr[5] );

you are passing the address of memory after teh last element of the array.

You need to write

project_team( arr );

In this call of scanf

scanf("%[^\n]s",str);

remove the character 's' from the format string

scanf(" %[^\n]",str);

It would be even more safer to write

scanf("            
  • Related