Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

c - Access stored char[] variable inside function from the main function

In my getUserInfo function I am returning the user's full name (first and last) to the main function. Inside getUserInfo I am also creating a username using the first initial, followed by the user's last name and their lucky number. However, when I go to print off the user's full name, followed by their username inside the main, I have no way of accessing the user's username.

These are my teacher's specific instructions: Store the person's username in the string passed in as a formal parameter to getUserInfo. Return the person's full name as a string (char*) from getUserInfo. Print off the person's full name, followed by their username inside the main function.

Here is my code:

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

char* getUserInfo(char username[]){
  char* fullname;
  char fname[20];
  char lname[20];
  int luckyNum;
  printf("Enter your first and last name: ");
  scanf("%s %s",fname, lname);
  printf("Enter your lucky number: ");
  scanf("%d", &luckyNum);
  
  char firstLetter[10];
  firstLetter[0] = fname[0];
  char luckyChars[10];
  sprintf(luckyChars, "%d", luckyNum);
  
  char* fullnameCopy = (char*)malloc(sizeof(char)*20);
  fullname = strcat(fname, " ");
  fullname = strcat(fullname, lname);
  strcpy(fullnameCopy, fullname);

  username = strcat(firstLetter, lname);
  username = strcat(username, luckyChars);
  
  return fullnameCopy;
}

int main() {
  char *fullname;
  char username[60];
  fullname = getUserInfo(username);
  printf("%s's username is %s.
", fullname, username);
  free(fullname);

  return 0;
}
question from:https://stackoverflow.com/questions/65932413/access-stored-char-variable-inside-function-from-the-main-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...