LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   problem printing pointer (https://www.linuxquestions.org/questions/programming-9/problem-printing-pointer-4175442329/)

doughyi8u 12-20-2012 11:18 AM

problem printing pointer
 
I have the following code:
Code:

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

char *my_strcpy(char *dest, char *source);

int main(int argc, char *argv[])
{
  char ptr1[] = "this is a string";
  char ptr2[80], *ret;
  ret = my_strcpy(ptr2, ptr1);
  /*puts(ret);*/
  puts(ptr2);
  system("PAUSE");       
  return 0;
}

char *my_strcpy(char *dest, char *source)
{
  int i = 0;
  while (*source) {
        *(dest++) = *(source++);
  }     
    *(dest) = '\0';
    puts(dest);    /*this doesn't print*/
    return dest;
}

The line in question has a comment in red. It Won't print but it does print ptr2 in main. I'm confused.

orgcandman 12-20-2012 11:35 AM

On the line in question, the value of dest is not the same as the value of ptr2.

Additionally, the value of ret, in the other commented puts will not be the same as ptr2.

Think about it a bit - you've been incrementing dest - where does it point on the line in question?

doughyi8u 12-20-2012 11:53 AM

How do I return dest and make it work? I tried passing it like so:
Code:

return &dest[0];
But that didn't work.
I also tried return *(dest - (strlen(source)));
but that didn't work either.

orgcandman 12-20-2012 02:21 PM

You need to think about what your variables hold a bit more. You actually don't need to declare anything new, but need to make use of something you're not.

I suggest another glance through the K&R C.

KenJackson 12-21-2012 06:20 AM

Code:

char *my_strcpy(char *dest, char *source)
{
    char *original_dest = dest;
    while (*source) {
        *dest++ = *source++;
    }     
    *dest = '\0';
    puts(original_dest);
    return original_dest;
}

I also removed some superfluous parentheses.

orgcandman 12-26-2012 10:20 AM

Quote:

Originally Posted by KenJackson (Post 4854285)
Code:

char *my_strcpy(char *dest, char *source)
{
    int i = 0;
    while (*source) {
        *dest++ = *source++; ++i;
    }     
    *dest = '\0';
    puts(dest - i);
    return dest - i;
}


Emphasis on the red lines, for a way of writing the implementation without declaring a new variable from the code written. NOTE: I support Ken's approach. Just wanted to make sure the OP understood my earlier comment.


All times are GMT -5. The time now is 02:50 AM.