Thread: programming errors

  1. #1
    Registered User
    Join Date
    Jun 2010
    Posts
    4

    Unhappy programming errors

    Hi all,

    Can someone help me understanding why the following code works well ?????
    Code:
    #include<stdio.h>
    
    int main()
    {
            char str[20]="hello";
            char * const p=str;
            *p='M';
            printf("%s\n",str);
            return 0;
    }
    what this char * const p means ????

    Thanks in advance.......

    Regards
    C_Enthuaist

  2. #2
    ... kermit's Avatar
    Join Date
    Jan 2003
    Posts
    1,534
    It means that p is a const pointer to char. In other words, you can't make it point somewhere else, though you can (as your example suggests) change the contents of the variable it points to. Consider your code:

    Code:
    char str[] = "hello";
    char *const p = str;
    str[] Is not const, but p is. Once you assign the address of str[] to p, that's it; you can't reassign a different address to p.

    Code:
    #include<stdio.h>
    
    int main()
    {
        char str[] = "hello";
        char str_2[] = "world";
        char *const p = str;
        *p = 'M';
        printf("%s\n", str);
        p = str_2;                  /* Compiler will complain */
        return 0;
    }
    Last edited by kermit; 06-18-2010 at 07:18 PM.

  3. #3
    Registered User
    Join Date
    Jun 2010
    Posts
    4
    hi kermit,

    Changing your following code a little bit will create a different error....
    char str[] = "hello";
    char *const p = str;
    Changing the above to...

    Code:
    har str[] = "hello";
    const char *p = str;
    This will make the compiler to report error at following line...

    Code:
    #include<stdio.h>
    
    int main()
    {
        char str[] = "hello";
        char str_2[] = "world";
        char *const p = str;
        *p = 'M';                           /* Compiler will complain */
        printf("%s\n", str);
        p = str_2;                 
        return 0;
    }
    So now please help me in understanding what is the difference between these two definitions...

    Thanks in advance.....

    Regards
    C_Enthuaist

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Now what the pointer points to is treated as const, so you should not change it through the pointer.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    ... kermit's Avatar
    Join Date
    Jan 2003
    Posts
    1,534
    C_Enthusiast,

    When you read these types of declarations, try doing it from right to left:

    Code:
    char *const p;
    Think of the above as "p is a const pointer to char."

    Code:
    const char *p;
    Now this time, reading from right to left, "p is a pointer to char which (i.e., the char variable) is also const."

  6. #6
    Registered User
    Join Date
    Jun 2010
    Posts
    22

    gets function

    Hi all,

    Thanks for clearing my doubts about the previous questions...... I am grateful to all of you...

    Now I am using gets() functions to accept a string but the gcc compiler reports the following warning at compilation time....
    Code:
    Test.c:(.text+0x24): warning: the `gets' function is dangerous and should not be used.
    Please help me in understanding the reasons for this warning.... Thanks in advance

    Regards
    C_Enthusiast

  7. #7
    Just a pushpin. bernt's Avatar
    Join Date
    May 2009
    Posts
    426
    Please help me in understanding the reasons for this warning.... Thanks in advance
    Lucky, lucky you... we've got a 7 page thread on this from a couple weeks ago.

    gets() not so bad
    Consider this post signed

  8. #8
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    When you have a new question, start a new thread.

    Anyway, that's because gets() is an old function which cannot prevent buffer overflows. It has been superseeded by other functions.

    Use fgets instead:
    Code:
    char buffer[256];
    fgets(buffer,256,stdin);
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  9. #9
    Registered User
    Join Date
    Jun 2010
    Posts
    22
    Quote Originally Posted by bernt View Post
    Lucky, lucky you... we've got a 7 page thread on this from a couple weeks ago.

    gets() not so bad
    The thread is to long and shook my head.... But it was really helpful... Thanks

    Anyway, that's because gets() is an old function which cannot prevent buffer overflows. It has been superseeded by other functions.
    Ok so I got why gets() is bad...

    But I want to know that is using getline() for accepting accepting strings is better or not... As getline can automatically expand the size of buffer when length of string exceeds the size of buffer... or I shall use fgets() only.....

    Please help... Thanks in advance

    Regards
    C_Enthusiast

  10. #10
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    is using getline() for accepting accepting strings is better or not
    Anything is better than gets. But yes getline is fine.

    One more thing about your const question. You can have both consts:
    Code:
    const char *const p = str;
    Now p cannot be changed to point to something else and the character it points to cannot be modified.

    Just to see if you really get it now, can you get your head around this?:
    Code:
    char * const p = str;
    char * const * pp = &p;

    What can and can't you do with pp?
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  11. #11
    Registered User
    Join Date
    Jun 2010
    Posts
    22

    Wink

    Quote Originally Posted by iMalc View Post
    Anything is better than gets. But yes getline is fine.

    One more thing about your const question. You can have both consts:
    Code:
    const char *const p = str;
    Now p cannot be changed to point to something else and the character it points to cannot be modified.

    Just to see if you really get it now, can you get your head around this?:
    Code:
    char * const p = str;
    char * const * pp = &p;

    What can and can't you do with pp?
    Hi iMalc,

    Well thanks for testing me also....

    p is a constant pointer and once made to point somewhere it cannot be made to point to any other location... But certainly p can change he contents of str[0]

    now pp is a pointer to a constant pointer so pp can be made to point to other locations but pp will not be able to change the contents of p

    following will be invalid...
    Code:
    char str1[]="hello";
    *pp=str1;
    but pp can change the contents of str[0];

    If I am wrong at any point please tell me about that.... I will be grateful to you..
    Thanks once again...

    Regards
    C_Enthusiast

  12. #12
    Registered User
    Join Date
    Jun 2010
    Posts
    22
    Hi all,

    Now one more error I am getting...

    Code:
    #include<stdio.h>
    
    int main()
    {
    	char str[20];
    	char ch;
    
    	printf("Enter a string: ");
    	scanf("%s",str);
    	
    	printf("\nEnter a character: ");
    	scanf("%c",&ch);
    	
    	return 0;
    
    }
    Why at runtime the code does not allow me to enter the character ????

    Regards
    C_Enthusiast

  13. #13
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Because there's a newline left in the stdin buffer. Read this:

    http://206.251.36.107/programming/stdin_buffer.mhtml
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  14. #14
    Third Eye Babkockdood's Avatar
    Join Date
    Apr 2010
    Posts
    352
    Code:
    #include<stdio.h>
    
    int main()
    {
            char str[20]="hello"; /* str is an array of 20 */
            char * const p=str; /* p points to str */
            *p='M'; /* Since p points to str, this statement replaces the first byte in str with 'M' */
            printf("%s\n",str); /* str = "Mello" */
            return 0;
    }

  15. #15
    Registered User
    Join Date
    Jun 2010
    Posts
    22

    Angry

    Hi all,

    I wrote the following code to add two very long positive integers... Numbers are stored in doubly linked list....But it gives segmentation fault... Can someone please check it and help....

    Code:
    #include<stdio.h>
    #include<malloc.h>
    
    #define MAX 100000
    
    struct node
    {
    	int info;
    	struct node *right;
    	struct node *left;
    };
    typedef struct node node;
    
    struct decision
    {
    	char big;
    	char opr;
    	char sign_of_result;
    };
    typedef struct decision decision;
    
    struct stackNode
    {
    	char info;
    	struct stackNode *next;
    };
    typedef struct stackNode stackNode;
    
    struct stack
    {
    	stackNode *top;
    };
    typedef struct stack stack;
    
    node* getNode(void);
    void getNumber(node*);
    void insertLeft(node*,int);
    void insertRight(node*,int);
    void freeNode(node*);
    decision* compare(node*,node*);
    void traverse(node*);
    void add(node*,node*,decision*);
    void push(stack*,char);
    char pop(stack*);
    int empty(stack*);
    
    int main()
    {
    	node *p,*q;
    	decision *d;
    
    	d=(decision*)malloc(sizeof(decision));	
    
    	p=getNode();
    	p->right=p;
    	p->left=p;
    
    	q=getNode();
    	q->right=q->left=q;
    
    	printf("\nEnter first number: ");
    	getNumber(p);
    /*...Using gdb I came to know that here is the error....
    	printf("\nEnter second number: ");
    	getNumber(q);
    
    	d=compare(p,q);
    
    	if(d->opr=='a')
    		add(p,q,d);
    
    	else
    		diff(p,q,d);
    
    	return 0;
    }
    
    node* getNode(void)
    {
    	node *ptr;
    	ptr=(node*)malloc(sizeof(node));
    	ptr->left=NULL;
    	ptr->right=NULL;
    	return ptr;
    }
    
    void insertLeft(node *ptr,int info)
    {
    	node *temp=getNode();
    	temp->info=info;
    	temp->left=ptr->left;
    	ptr->left->right=temp;
    	ptr->left=temp;
    	temp->right=ptr;
    }
    
    void insertRight(node *ptr,int info)
    {
    	node *temp=getNode();
    	temp->info=info;
    	temp->right=ptr->right;
    	ptr->right->left=temp;
    	ptr->right=temp;
    	temp->left=ptr;
    
    printf("\nNumber being entered: %d\n",info);
    }
    
    
    void getNumber(node *ptr)
    {
    	int i=1,num=0,iter_count=0,count=0;
    	char ch,sign;
    	stack *s;
    	s->top=NULL;
    
    	ch=getchar();
    
    	if(ch=='-')
    		sign=ch;
    	
    	else
    	{
    		push(s,ch);
    		sign='+';
    	}
    
    	while((ch=getchar())!='\n')
    		push(s,ch);
    
    	while(!empty(s))
    	{printf("\n\nfunc called\n\n");
    		while(!empty(s) && iter_count!=4)
    		{
    			ch=pop(s);
    			num=num+(ch-'0')*i;
    			iter_count++;
    			i*=10;
    		}
    		iter_count=0;
    		count++;
    		insertRight(ptr,num);
    		num=0;
    		i=1;
    	}
    
    	if(sign=='-')
    		ptr->info=count*-1;
    	else
    		ptr->info=count;
    
    printf("\n\nfnction successfully executed\n\n");
    }
    
    void freeNode(node *ptr)
    {
    	ptr->left->right=ptr->right;
    	ptr->right->left=ptr->left;
    	ptr->right=NULL;
    	ptr->left=NULL;
    	free(ptr);
    }
    
    decision* compare(node *p,node *q)
    {
    	node *r=p;
    	node *s=q;
    	decision *d;
    	
    	d=(decision*)malloc(sizeof(decision));
    	d->big='p';
    	d->opr='a';	
    	d->sign_of_result='+';
    
    	if(p->info>0 && q->info>0)
    		return d;
    	else if(p->info<0 && q->info<0)
    	{
    		d->sign_of_result='-';
    		return d;
    	}
    
    	else
    		d->opr='s';
    
    	if(abs(p->info)==abs(q->info))
    	{
    		r=r->left;
    		s=s->left;
    		
    		while(r->info==s->info)
    		{
    			r=r->left;
    			s=s->left;
    		}
    
    		if(r!=p && s!=q)
    			if(r->info<s->info)
    			{
    				d->big='q';
    				d->sign_of_result='+';
    			}
    
    	}
    	else if(abs(p->info)<abs(q->info))
    	{
    		d->big='q';
    		d->sign_of_result='-';
    	}
    
    	return d;
    
    }
    
    void traverse(node *ptr)
    {
    	printf("Result is: ");
    
    	if(ptr->info<0)
    		printf("-");
    
    	node *p=ptr->right;
    
    	while(p!=ptr)
    	{
    		printf("%d",p->info);
    		p=p->right;
    	}
    
    	printf("\n\n");
    }
    
    void add(node *p,node *q,decision *d)
    {
    	node *r=getNode();
    	node *s,*t;
    	int count=0,carry=0,total=0;
    
    	r->left=r->right=r;
    	s=p->right;
    	t=q->right;
    
    	while(s!=p && t!=q)
    	{		
    		total=s->info+t->info+carry;
    		carry=total/MAX;
    		total=total%MAX;
    
    		insertRight(r,total);
    		count++;
    
    		s=s->right;
    		t=t->right;
    	}
    
    	while(s!=p)
    	{
    		total=s->info+carry;
    		carry=total/MAX;
    		total=total%MAX;
    
    		insertRight(r,total);
    		count++;		
    
    		s=s->right;
    		t=t->right;
    	}
    
    	while(t!=q)
    	{
    		total=t->info+carry;
    		carry=total/MAX;
    		total=total%MAX;
    
    		insertRight(r,total);
    		count++;		
    
    		s=s->right;
    		t=t->right;
    	}
    
    	if(carry!=0)
    	{
    		insertRight(r,carry);
    		count++;
    	}
    
    	if(d->sign_of_result=='-')
    		r->info=count*-1;
    	else
    		r->info=count;		
    
    	traverse(r);	
    }
    
    void push(stack *s,char info)
    {
    	stackNode *ptr=(stackNode*)malloc(sizeof(stackNode));
    	ptr->next=NULL;
    	ptr->info=info;
    
    	if(s->top==NULL)
    		s->top=ptr;
    	else
    	{
    		ptr->next=s->top;
    		s->top=ptr;
    	}
    }
    
    char pop(stack *s)
    {
    	char info=s->top->info;
    	stackNode *ptr=s->top;
    	s->top=s->top->next;
    	ptr->next=NULL;
    	free(ptr);
    	return info;
    }
    
    int empty(stack *s)
    {
    	return(s->top==NULL?1:0);
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Ten Errors
    By AverageSoftware in forum Contests Board
    Replies: 0
    Last Post: 07-20-2007, 10:50 AM
  2. Unknown Errors in simple program
    By neandrake in forum C++ Programming
    Replies: 16
    Last Post: 04-06-2004, 02:57 PM
  3. Stupid compiler errors
    By ChrisEacrett in forum C++ Programming
    Replies: 9
    Last Post: 11-30-2003, 05:44 PM
  4. Help me with these errors... :-(
    By major_small in forum C++ Programming
    Replies: 6
    Last Post: 09-07-2003, 08:18 PM
  5. errors in class(urgent)
    By ayesha in forum C++ Programming
    Replies: 2
    Last Post: 11-10-2001, 06:51 PM