Thread: string pointer porblem

  1. #1
    Registered User
    Join Date
    Jun 2003
    Posts
    51

    string pointer problem

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    
    struct list1{
    	char *name;
    	struct list1 *next;
    };
    
    void addname(char name[],struct list1 **node)
    {
    	struct list1 *x,*ptr;
    	x= malloc(sizeof(struct list1));
    
    	x->name=name;
    	x->next=NULL;
    	ptr=*node;
    
    	if(*node==NULL)
    		*node=x;
    	else{
    		while(ptr->next!=NULL)
    			ptr=ptr->next;
    		ptr->next=x;
    	}
    }
    
    int main(void)
    {
    	struct list1 *nList,*ptr;
    	FILE *fileptr;
    	char name[BUFSIZ],dump;
    	int counter,mark=0,sum;
    	nList= NULL;
    
    	fileptr=fopen("namelist.txt","r");
    	if(fileptr==NULL)
    		perror("Unable to open file");
    	else{
    		while(fscanf(fileptr,"%[^\n]\n",name,&dump)!=EOF)
    		{
    			printf("%s\n",name);
    			addname(name,&nList);
    		}
    		for(ptr=nList;ptr!=NULL;ptr=ptr->next)
    		{
    			printf("%s\n", ptr->name);
    		}
    	return 0;
    }
    My problem is the name var in the linked list aways point to the same address .... how can i make string store on different address? I'm confusing with the string array and string pointer...
    Last edited by megablue; 07-12-2004 at 05:16 AM.

  2. #2
    ~viaxd() viaxd's Avatar
    Join Date
    Aug 2003
    Posts
    246
    Code:
    	x->name=name;
    you should use strcpy() instead, and change your structure to smt like
    Code:
    struct list1{
    	char name[100];
    	struct list1 *next;
    };
    or you can malloc name if you want it a pointer.

    also be sure to free() the memory you've malloc()'ed when you're done.
    Last edited by viaxd; 07-12-2004 at 08:56 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointer to String and Pointer to Char
    By vb.bajpai in forum C Programming
    Replies: 3
    Last Post: 06-15-2007, 03:03 PM
  2. Pointer to array of string and Array of Pointer to String
    By vb.bajpai in forum C Programming
    Replies: 2
    Last Post: 06-15-2007, 06:04 AM
  3. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 09:11 AM
  4. Custom String class gives problem with another prog.
    By I BLcK I in forum C++ Programming
    Replies: 1
    Last Post: 12-18-2006, 03:40 AM
  5. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM