C Board  

Go Back   C Board > General Programming Boards > C Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 11-07-2009, 03:38 PM   #1
Registered User
 
Join Date: Oct 2009
Posts: 22
Strings and structs

I am getting this following error for the code at the bottom of this post:
"error: incompatible types in assignment"

The error is referring to these two lines of code:
Code:
	  curr->product = "widget";
	  curr->description = "a useful thing.";
Code:
#include<stdlib.h>
#include<stdio.h>

struct node {
   char product[20];
   char description[50];
   float price;
   struct node * next;
};

typedef struct node item;

int main() {
   item * curr, * head;
   

   head = NULL;

   for(int i=1;i<=10;i++) {
      curr = (item *)malloc(sizeof(item));
	  curr->product = "widget";
	  curr->description = "a useful thing.";
      curr->price = i;
      curr->next  = head;
      head = curr;
   }

   curr = head;

   while(curr) {
      printf("%s\n", curr->product);
	  printf("%s\n", curr->description);
	  printf("%f\n", curr->price);
      curr = curr->next ;
   }
   
   curr = head;
   return 0;
}
Roger is offline   Reply With Quote
Old 11-07-2009, 04:06 PM   #2
Registered User
 
Join Date: Oct 2006
Location: Canada
Posts: 848
Code:
  curr->product = "widget";
	  curr->description = "a useful thing.";
You cant directly assign the strings this way, use strcpy: strcpy - C++ Reference (simple examples are at the bottom of that page).

Also, you need to "free" everything that you "malloc", right now the code produces a memory leak of (10*(sizeof(item)) bytes.
nadroj is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Some questions with strings, vectors, references... samus250 C++ Programming 11 07-10-2008 02:31 PM
Input String And Integers From File And Sort By Strings xfactor C Programming 9 03-17-2006 12:44 PM
Array of Structs question WaterNut C++ Programming 10 07-02-2004 02:58 PM
Wokring with strings in structs micke C Programming 1 06-12-2003 01:24 PM
Strings and Structures Kinasz C Programming 3 02-23-2003 03:46 AM


All times are GMT -6. The time now is 03:36 PM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.0 RC2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22