'How do I initiate multiple strings in malloc in C
I'm trying to learn C and I have an asignment to use malloc and struct and I have it print out the queue number but the string wont print. I have attached a picture of the print, but only works when strcpy is commented out and I cant figure it out.
Could anyone explain what I'm doing wrong and what should be done?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct car
{
int queue;
char *Regnr;
char *Manufactor;
char *WashType;
char *CarId;
struct car *next;
};
typedef struct car CarWash;
/* print the list out from ... */
void printlist (CarWash * head)
{
CarWash *temp = head;
while (temp != NULL)
{
printf ("%d\t\t %s\t\t %s\t\t %s\t \n", temp->queue, temp->Regnr,
temp->Manufactor, temp->WashType);
temp = temp->next;
}
printf ("\n");
};
CarWash *create_new_queue(int val,char CarId)
{
CarWash *result = malloc (sizeof (CarWash));
char strcpy(char Regnr, char CarId);
result->Regnr = CarId;
result->queue = val;
result->next = NULL;
return result;
};
edited
int
main ()
{
int queue;
char Regnr[10];
char Manufactor[10];
char WashType[10];
char CarId[10];
CarWash *head;
CarWash *tempB;
FILE *fp;
fp = fopen ("Car wash.txt", "r");
fscanf (fp, "%d%s%s%s", &queue, Regnr, Manufactor, WashType);
fclose (fp);
printf (" \n"); //voodoo to show my printlist
tempB = create_new_queue (queue, Regnr);
head = tempB;
printf ("%s\t %s\t\t %s\t %s\n", "kø plads", "Regnr", "Manufactor",
"vaske type");
printlist (head);
return 0;
}
edited
What gets printed:
Solution 1:[1]
You probably want this:
struct car
{
int queue;
char Regnr[10]; // don't declare pointers but arrays
char Manufactor[10];
char WashType[10];
char CarId[10];
struct car *next;
};
And the corrected create_new_queue function:
CarWash* create_new_queue(int val, char *CarId) // add the *, CarId is not a char
{
CarWash* result = malloc(sizeof(CarWash));
strcpy(result->Regnr, CarId); // actually call strcpy
result->queue = val;
result->next = NULL;
return result;
};
I recommend you read the chapter dealing with pointers and the chapter dealing with strings in your learning material.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jabberwocky |

