Randy G.
Randy G.

Reputation: 111

Printing a string from a linked list using a function to store and printf to display

I appreciate any help I can get. I am currently having an issue printing from a linked list after storing a string. Ideally, I'd be able to display the stored string after handing it through the function and printing it from another function. The code below illustrates my issue and is very similar to my working code. I cannot tell why it won't print. The best I have had so far is (null) and that...for obvious reasons won't cut it. Thanks in advance. I'm still very new to coding in c.

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

struct class{
  char *prefix_name; // will store something like "MAC 544"
  int  cred_hours;
  int  crn_number;
};
struct student{
  int id;
  char f_name[50];
  char l_name[50];
  struct class c_one;
};

char stu_test(struct student *info){
  char x;
  x = "MAC 344";
  return x;
}

int main() {
  struct student info[100];

  info[0].c_one.prefix_name=stu_test(info);

  printf("%s\n", info[0].c_one.prefix_name);


  return EXIT_SUCCESS;
}

Here is the switch that I will use.....hopefully

char *crnName(int crn){
  char *name;
  switch (crn) {
    case 4587:
      name="MAT 236";
    break;
    case 4599:
      name="COP 220";
    break;
    case 8997:
      name="GOL 124";
    break;
    case 9696:
      name="COP 100";
    break;
    case 1232:
      name="MAC 531";
    break;
    case 9856:
      name="STA 100";
    break;
    case 8520:
      name="TNV 400";
    break;
    case 8977:
      name="CMP 100";
    break;
  }
  return name;
} 

Upvotes: 1

Views: 47

Answers (1)

H.S.
H.S.

Reputation: 12669

Look at stu_test() function:

char stu_test(struct student *info){
  char x;
  x = "MAC 344";
  return x;
}

"MAC 344" is a string literal and you are assigning it to x which is of type char. Compiler must be giving warning message for this. I am using gcc compiler and getting warning message:

prg.c:19:5: warning: incompatible pointer to integer conversion assigning to 'char' from 'char [8]' [-Wint-conversion]
  x = "MAC 344";

You should change the type of x and return type of stu_test() function to char *:

char * stu_test(struct student *info){
  char * x;
  x = "MAC 344";
  return x;
}

Upvotes: 1

Related Questions