Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing char pointer in C

Tags:

c

char

pointers

Okay so I am trying to pass a char pointer to another function. I can do this with an array of a char but cannot do with a char pointer. Problem is I don't know the size of it so I cannot declare anything about the size within the main() function.

#include <stdio.h>

void ptrch ( char * point) {
    point = "asd";
}

int main() {
    char * point;
    ptrch(point);
    printf("%s\n", point);
    return 0;
}

This does not work however, these two works:

1)

#include <stdio.h>

int main() {
    char * point;
    point = "asd";
    printf("%s\n", point);
    return 0;
}

2)

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

void ptrch ( char * point) {
    strcpy(point, "asd");
}

int main() {
    char point[10];
    ptrch(point);
    printf("%s\n", point);
    return 0;
}

So I am trying to understand the reason and a possible solution for my problem

like image 308
Sarp Kaya Avatar asked Jan 15 '13 04:01

Sarp Kaya


2 Answers

This should work since pointer to the char pointer is passed. Therefore any changes to the pointer will be seen outside thereafter.

void ptrch ( char ** point) {
    *point = "asd";
}

int main() {
    char * point;
    ptrch(&point);
    printf("%s\n", point);
    return 0;
}
like image 71
hmatar Avatar answered Sep 29 '22 22:09

hmatar


void ptrch ( char * point) {
    point = "asd";
}

Your pointer is passed by value, and this code copies, then overwrites the copy. So the original pointer is untouched.

P.S. Point to be noted that when you do point = "blah" you are creating a string literal, and any attempt to modify is Undefined behaviour, so it should really be const char *

To Fix - pass a pointer to a pointer as @Hassan TM does, or return the pointer as below.

const char *ptrch () {
    return "asd";
}

...
const char* point = ptrch();
like image 44
Karthik T Avatar answered Sep 29 '22 23:09

Karthik T