传递字符指针用C [英] Passing char pointer in C

查看:179
本文介绍了传递字符指针用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好了,所以我想一个字符指针传递给另一个函数。我能做到这一点有一个字符数组,但不能以字符指针做。问题是我不知道它的大小,所以我不能对的main()函数内声明的大小事情。

 的#include<&stdio.h中GT;无效ptrch(字符*点){
    点=ASD
}诠释主(){
    字符*点;
    ptrch(点);
    的printf(%S \\ N,点);
    返回0;
}

然而,这并不正常工作,这两部作品:

1)

 的#include<&stdio.h中GT;诠释主(){
    字符*点;
    点=ASD
    的printf(%S \\ N,点);
    返回0;
}

2)

 的#include<&stdio.h中GT;
#包括LT&;&string.h中GT;无效ptrch(字符*点){
    的strcpy(点,ASD);
}诠释主(){
    焦点[10];
    ptrch(点);
    的printf(%S \\ N,点);
    返回0;
}

所以,我想了解我的问题的原因和可能的解决方案


解决方案

 无效ptrch(字符*点){
    点=ASD
}

您指针按值,这code 拷贝通过,那么将覆盖副本即可。所以原来的指针不变。

P.S。点要注意的是,当你做点=嗒嗒要创建一个字符串,任何企图的修改未定义行为,所以应该真正的 为const char *

解决 - 一个指针传递给一个指针作为@Hassan TM做,或指针返回如下

 为const char * ptrch(){
    返回ASD
}...
为const char *点= ptrch();

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

解决方案

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();

这篇关于传递字符指针用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆