NO

Author Topic: pointers and arrays  (Read 8335 times)

manichandra

  • Guest
pointers and arrays
« on: February 12, 2012, 05:09:05 AM »
what is the error in this ??

can anyone tell me appropriate way to implement a string copy function using malloc and pointers
(and same question  also using double pointers )???



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

void newStrCpy(char* q, char* p);

int main (void)
{
   
    char *src=0;
    printf("\n----------------------------------------");
   printf("\nPROGRAM TO COPY THE CONTENTS OF ONE STRING TO ANOTHER ");
   printf("\n----------------------------------------");
   printf("\n\n\t ENTER A STRING...: ");
    scanf("%s",src);
    char *dst =(char*) malloc(sizeof(*src));
    newStrCpy(src,dst);
    printf("\n\t copied string is..: %s\n",dst);
   
    return 0;
}

void newStrCpy(char* q, char* p)
{
   
    int i=0;
      while(*(q+i)!='\0')
      {
        *p = *q;
          p++;
          q++;
    }   
    *p='\0';
   
}

Offline Bitbeisser

  • Global Moderator
  • Member
  • *****
  • Posts: 772
Re: pointers and arrays
« Reply #1 on: February 12, 2012, 05:47:14 AM »
Well, not knowing if this is some kind of homework, I give you only two hints:

- You don't allocate any space for the input string (src)
- check how much space you allocate for the destination string (dst)

Ralf

CommonTater

  • Guest
Re: pointers and arrays
« Reply #2 on: February 12, 2012, 05:55:26 AM »
In addition to Bitbessier's comments...

There is no reason to typecast the return value of malloc in C99 (That's a C++, thing)
You also forgot to free the allocated space.

I strongly suggest you put your text cursor on the word malloc() in your source code and press F1 on your keyboard...



Offline Bitbeisser

  • Global Moderator
  • Member
  • *****
  • Posts: 772
Re: pointers and arrays
« Reply #3 on: February 12, 2012, 06:12:04 AM »
You also forgot to free the allocated space.
Well, for doing so, (s)he has to allocate it properly in the first place...  ;)

Ralf

CommonTater

  • Guest
Re: pointers and arrays
« Reply #4 on: February 12, 2012, 03:06:07 PM »
You also forgot to free the allocated space.
Well, for doing so, (s)he has to allocate it properly in the first place...  ;)

Ralf

:D 

I remember when I was trying to get my head around pointers.  After years of Pascal, where pointers are used only rarely, it seemed like some fresh hell come to visit... my first few attempts were just disastrous... but I finally got the hang of it ... or at least I think I have... one can never get smug around C.




sanide

  • Guest
Re: pointers and arrays
« Reply #5 on: February 12, 2012, 04:26:37 PM »
Code
Code: [Select]
#include <stdio.h>
#include<stdlib.h>
#include<string.h>

void newStrCpy(char* q, char* p);

int main (void)
{
   
    char src[255]="\00";
    printf("\n----------------------------------------");
   printf("\nPROGRAM TO COPY THE CONTENTS OF ONE STRING TO ANOTHER ");
   printf("\n----------------------------------------");
   printf("\n\n\t ENTER A STRING...: ");
    scanf("%s",src);
    char *dst = malloc(strlen(src)+1);
    newStrCpy(src,dst);
    printf("\n\tcopied string is..: %s\n",dst);
    free(dst);
    return 0;
}

void newStrCpy(char* q, char* p)
{
       while( *q != '\0' )
      {
        *p = *q;
        p++;
        q++;
      }   
    *p='\0';
   
}



sanide :)

CommonTater

  • Guest
Re: pointers and arrays
« Reply #6 on: February 12, 2012, 06:16:39 PM »
Code
Code: [Select]
#include <stdio.h>
#include<stdlib.h>
#include<string.h>

void newStrCpy(char* q, char* p);

int main (void)
{
   
    char src[255]="\00";
    printf("\n----------------------------------------");
   printf("\nPROGRAM TO COPY THE CONTENTS OF ONE STRING TO ANOTHER ");
   printf("\n----------------------------------------");
   printf("\n\n\t ENTER A STRING...: ");
    scanf("%s",src);
    char *dst = malloc(strlen(src)+1);
    newStrCpy(src,dst);
    printf("\n\tcopied string is..: %s\n",dst);
    free(dst);
    return 0;
}

void newStrCpy(char* q, char* p)
{
       while( *q != '\0' )
      {
        *p = *q;
        p++;
        q++;
      }   
    *p='\0';
   
}



sanide :)

Ok... I wouldn't suggest just giving out answers like that, since this is likely a homework assignment and the OP won't learn anything by copying other people's code...

However...
1) The intializer for your array is incorrect; should be ... char src[255] = {0};
2) scanf() is not the best way to get a string ... use fgets() to prevent buffer overflows.
3) The function will be more universal if you allocate inside and return a pointer.
4) The return from malloc() should be checked for success
5) Although not really an error you should avoid overdecorating the screen... simple is smart.
6) Although C-99 doesn't require it, you should declare your vairables at the top of functions.

Code: [Select]
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
 
#pragma warn(disable: 2030)
 
char* newStrCpy(char* src)
  {  char *p;                   // copy pointer
     char *dst = malloc((strlen(src) + 1) * sizeof(char));
     if (!dst)                     // make sure it worked
       return NULL;
     p = dst;     
     while(*p++ = *src++);          // copy
     return dst; }     

int main (void)
{
    char src[255]={0};   // input buffer
    char *dst = NULL;    // pointer to copy
    char *nl;            // pointer to newline
    printf("\nPROGRAM TO COPY THE CONTENTS OF ONE STRING TO ANOTHER\n\n");
    printf("Enter some text : ");
    fgets(src,254,stdin);
 
    nl = strchr(src,'\n');           // remove trailing newline
    if (nl)
      *nl = 0;
 
    printf("\nOriginal :  %s\n",src);
    dst = newStrCpy(src);
    printf("Copy     :  %s\n",dst);

    free(dst);
    return 0;
}

 
« Last Edit: February 12, 2012, 06:20:49 PM by CommonTater »

sanide

  • Guest
Re: pointers and arrays
« Reply #7 on: February 12, 2012, 07:33:33 PM »

#include <stdio.h>
int main (void)
{int a[23]={89,111,117,39,114,101,32,115,111,32,102,117,108,108,32,111,102,32,115,104,105,116,0};
for(int i=0;i<23;i++)printf("%c",a);return 0;}



sanide

CommonTater

  • Guest
Re: pointers and arrays
« Reply #8 on: February 12, 2012, 08:47:25 PM »

#include <stdio.h>
int main (void)
{int a[23]={89,111,117,39,114,101,32,115,111,32,102,117,108,108,32,111,102,32,115,104,105,116,0};
for(int i=0;i<23;i++)printf("%c",a);return 0;}

sanide

Oh my aren't we the clever one...

1) You should always post code segments in code /code tags ... the forum ate your array index.

2) Your code setup leaves a lot to be desired... perhaps you should have a look at this link

3) As a rule people who cannot accept criticism and suggestions don't last very long in the workplace. You may want to rethink your reactions in these cases.
 
4) I'd wager I was programming before you were born... (started in 1977)


 

Offline Bitbeisser

  • Global Moderator
  • Member
  • *****
  • Posts: 772
Re: pointers and arrays
« Reply #9 on: February 12, 2012, 11:22:43 PM »

#include <stdio.h>
int main (void)
{int a[23]={89,111,117,39,114,101,32,115,111,32,102,117,108,108,32,111,102,32,115,104,105,116,0};
for(int i=0;i<23;i++)printf("%c",a);return 0;}



sanide
Clean yourself up  first.

CommonTater

  • Guest
Re: pointers and arrays
« Reply #10 on: February 12, 2012, 11:31:14 PM »
Clean yourself up  first.

He's off to a great start, for a guy with a post count of 2 ... Yep only 2 posts and already flaming.

manichandra

  • Guest
Re: pointers and arrays
« Reply #11 on: February 13, 2012, 06:26:58 AM »
is this correct ??? and can anybody tell me how to do using double pointers and withoting returning the function like
void stringcopy(char **, char *)

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

char* newStrCpy(char* p, char*s);

int main(void){
   
    char *src = "mani chandra";
    char *dst;
   
    printf("%s",newStrCpy(dst,src));
   
    return 0;
}

char* newStrCpy(char* p, char* s){
   
    int i=0;
    p = malloc((strlen(s)+1)*sizeof(char));
    do
    {
        *(p+i)=*(s+i);
        i++;
    }while(*(s+i)!='\0');
   
    return p;
   
}
   

manichandra

  • Guest
Re: pointers and arrays
« Reply #12 on: February 13, 2012, 06:54:34 AM »
thanks guys , this is a assignment question only. i did the assignment long back declaring array like
 "char src[32]={0};" in the main .
But i have seen some codes they used "char *src" and dint takes the user input into the string . and in one code i saw double pointers.
by seeing that i am trying to do like that.
anyway thanks guys for clearing some basic points about pointers

CommonTater

  • Guest
Re: pointers and arrays
« Reply #13 on: February 13, 2012, 01:52:07 PM »
is this correct ??? and can anybody tell me how to do using double pointers and withoting returning the function like
void stringcopy(char **, char *)

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

char* newStrCpy(char* p, char*s);

int main(void){
   
    char *src = "mani chandra";
    char *dst;
   
    printf("%s",newStrCpy(dst,src));
   
    return 0;
}

char* newStrCpy(char* p, char* s){
   
    int i=0;
    p = malloc((strlen(s)+1)*sizeof(char));
    do
    {
        *(p+i)=*(s+i);
        i++;
    }while(*(s+i)!='\0');
   
    return p;
   
}

Since you are allocating inside the function and returning a pointer, there's no reason to have the first parameter in the function call... instead you should declare p as a local variable.
 
Also you are not checking the result of malloc() which can fail in an out of memory condition leaving you to write over memory you do not own... with potentially bizarre results.
 
So, your copy function should probably look something like this...
Code: [Select]

 char* newStrCpy(char* s){
    char *p;
    int i=0;
    p = malloc((strlen(s)+1)*sizeof(char));

    // copy only if malloc() succeeds
    if (p != NULL) {                 
      do {
          *(p+i)=*(s+i);
           i++;
        }  while(*(s+i)!='\0');
     }

    return p;
}

Also you are not calling free() to release the memory you allocated.  You should always release memory as soon as you are done with it and don't count on the program's exit to clean it up for you.  In larger applications, when functions are called multiple times you can get a phenomenon called "memory leaks" where you are soaking up more and more memory but actually using almost none of it. Worse still, if you are calling it in a loop and overwriting the local variable each time, you may not have the means to free() the memory at all.
 
Since you are allocating inside your function and not using any variable for the returned value it is very likely you will get memory leaks, since you have no means to release the memory. 
 
Thus, it would be better to write your main function like this...
Code: [Select]
int main(void){
   
    char *src = "mani chandra";
    char *dst;
     
    dst = newStrCpy(src);
 
    printf("%s", dst );
       
    if (dst != NULL)
      free(dst);

    return 0;
}

Double pointers are used when you want to change the value of the pointer itself ... A useful example would be a custom free() function that resets the pointer to NULL, like this:
Code: [Select]
void cFree(void **ptr)
  { free(*ptr);
     *ptr = NULL; }
 
// called with address of pointer, as...
 
cFree(&dst);
 

For your copy routine you could do this...
Code: [Select]

 void newStrCpy(char **p char *s){
    int i = 0;
    *p = malloc((strlen(s) + 1) * sizeof(char));

    if (*p != NULL) {
       do  {
           **(p + i) = *(s + i);
           i++;
        } while(*(s+i) != '\0');
   }
}
 
// called with address of destination, as...
char *p;
 
newStrCpy(&p,src);
 

However; it's probably a good idea to avoid using double and triple pointers as much as you can.  The possiblity of subtle programming errors increases sharply when you start getting clever with your code and you risk creating problems that defy analysis.  (Been there, done that, burned the T-Shirt!)
 
Remember... Simple is Smart.
 
« Last Edit: February 13, 2012, 02:12:34 PM by CommonTater »

manichandra

  • Guest
Re: pointers and arrays
« Reply #14 on: February 14, 2012, 03:14:13 AM »
i appreciate for your time tator.
thanks