Alex Kreinis
Alex Kreinis

Reputation: 147

Using pointers to make a new string in function

I am doing a bit of studying about C pointers and how to transfer them to functions, so I made this program

    #include <stdio.h>
char* my_copy(pnt);
void main()
{
    int i;
    char a[30];
    char* p,*pnt;
    printf("Please enter a string\n");
    gets(a);
    pnt = a;
    p = my_copy(pnt);
    for (i = 0; i < 2; i++)
        printf("%c", p[i]);

}
char* my_copy(char* pnt)
{
    char b[3];
    char* g;
    g = pnt;
    b[0] = *pnt;
    for (; *pnt != 0; pnt++);
    pnt--;
    b[1] = *pnt;
    b[2] = NULL;


    return b;
    }

It's supposed to take a string using only pointers and send a pointer of the string to the function my_copy and return a pointer to a new string which contains the first and the last letter of the new string. Now the problem is that the p value does receive the 2 letters but I can't seem to print them. Does anyone have an idea why?

Upvotes: 0

Views: 52

Answers (2)

user325117
user325117

Reputation:

You're returning an array from my_copy that you declared within the function. This was allocated on the stack and so is invalid when the function returns.

You need to allocate the new string on the heap:

#include <stdlib.h>

    b = malloc(3);
    if (b) {
        /* Do your funny copy here */
    }

Don't forget to free() the returned string when you've finished with it.

Upvotes: 1

melpomene
melpomene

Reputation: 85767

I see five issues with your code:

  1. char* my_copy(pnt); is wrong. A function prototype specifies the types of the parameters, not their names. It should be char *my_copy(char *).

  2. void main() is wrong. main should return int (and a parameterless function is specified as (void) in C): int main(void).

  3. gets(a); is wrong. Any use of gets is a bug (buffer overflow) and gets itself has been removed from the standard library. Use fgets instead.

  4. b[2] = NULL; is a type error. NULL is a pointer, but b[2] is a char. You want b[2] = '\0'; instead.

  5. my_copy returns the address of a local variable (b). By the time the function returns, the variable is gone and the pointer is invalid. To fix this, you can have the caller specify another pointer (which tells my_copy where to store the result, like strcpy or fgets). You can also make the function return dynamically allocated memory, which the caller then has to free after it is done using it (like fopen / fclose).

Upvotes: 1

Related Questions