C 中的 char 指针和 strcpy

标签 c pointers char strcpy

首先让我开始说我已经阅读了与该主题相关的所有问题,但找不到解决我的问题的方法。所有的答案似乎都是停止使用指针和字符(我需要这样做)或关于其他结构。

我需要创建一个返回整数的函数,但也保存过程的步骤,我将使用 snprintf 和指针将其保存为字符。我会留下基本的想法,但它比我要说的要复杂得多。

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


int sum_and_diff (int a, int b, int *res, char *text);

int main(void){
    int b = 2;
    int diff;
    char texto;

    printf("La suma de 5 y %d es %d\n", b, sum_and_diff(5, b, &diff, &texto));
    printf("La diferencia de 5 y %d es %d\n", b, diff);
    printf("El texto es %s\n", texto);
}



int sum_and_diff (int a, int b, int *res, char *text){
    char texto;
    int sum;

    //text = malloc(sizeof(char) * 254);
    //text = (char *)malloc(sizeof(char) * 254);
    sum = a + b;
    *res = a - b;
    texto = "Hola";
    strcpy(*text, texto);
    //strcpy(text, texto);
    return sum;
}

我想使用这个示例,因为它展示了如何在函数内部使用指针来获取更多信息,用于获取差异的相同过程不适用于字符类型。

与我的实际程序的唯一区别是变量“texto”从 snprintf 获取它的字符值(做我需要它做的事情,我已经通过在函数内部打印变量来检查)。问题在于让指针指向变量。

谢谢!如果它有所作为,我正在使用 gcc 4.9 进行编译。评论的内容是我尝试过但没有用的东西,还尝试了一些其他的细微变化。

最佳答案

在没有分配的情况下声明指向 char 的指针是错误的。 你看我的代码。 [c]

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

#define SIZE    8

int sum_and_diff (int a, int b, int *res, char *text);

int main(void)
{
    int b = 2;
    int diff;
    char *texto = (char *)malloc(SIZE);
    if (!texto)
        abort();
    printf("La suma de 5 y %d es %d\n", b, sum_and_diff(5, b, &diff, texto));
    printf("La diferencia de 5 y %d es %d\n", b, diff);
    printf("El texto es %s\n", texto);
    free(texto);
}

int sum_and_diff (int a, int b, int *res, char *text)
{
    char *texto = (char *)malloc(SIZE);
    int sum;
    if (!texto)
        abort();
    sum = a + b;
    *res = a - b;
    texto = "Hola";
    strcpy(text, texto);
    free(texto);
    return sum;
}

关于C 中的 char 指针和 strcpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40634573/

相关文章:

c - malloc 返回类型转换困惑

c - 在 C 语言中,为什么我可以看到一个值写在不同变量的数组末尾之后?

c - 是否可以在 C 中将 char[] 转换为 char*?

C 指针和 AT&T Movl 语法

python - 通过指向该函数的指针获取函数参数值?

c - 当函数返回 char 数组指针时,Valgrind 会报错

c - 使用字符指针的字符串

c++ - 学习 C,我的编译器已经知道 bool (Visual Studio 2017)

c - 使用双指针和 malloc 读取文件

c++ - 调试时找不到 "arm-elf-g++"