如何制作动态字符?

时间:2017-12-06 11:44:54

标签: c pointers dynamic char

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

void generarCadena(char *);
void generarDimension(int, void **, int);
void reallocarDimensiones(int , void **, int);

int main(void){
    char *caracter=NULL;
    generarCadena(&caracter);
    printf("%d", sizeof(caracter));
    printf("%s", &caracter);//I want to now why this doesn't print
    return 0;
}

void generarCadena(char *scaneado){
    unsigned int cont;
    char lector;
    generarDimension(1,&scaneado,sizeof(char));
    cont = 0;
    while(!scanf("%s", &scaneado)){
        while((strcpy(lector,getchar())) !='\n' && lector!=EOF){
           reallocarDimensiones(1,&scaneado[cont],sizeof(char));
           cont++;
        }
    }
    printf("%s", &scaneado);/*Inside de function it prints, 
    however, it doesn't print outside it*/
}//This function is for the dynamic char

void generarDimension(int bloques, void **ptr, int tamanho){
    *ptr = malloc(bloques * tamanho);
    if(*ptr==NULL){
        printf("No se pudo almacenar memoria\n");
    }
}//This function mallocs any given pointer
void reallocarDimensiones(int bloques, void **ptr, int tamanho){
    *ptr = realloc(*ptr,bloques * tamanho);
    if(*ptr==NULL){
        printf("No se pudo almacenar memoria\n");
    }
}//This function reallocs any given pointer

嗨,我现在想要如何在键盘上写入时动态存储一个字符,所以我为它做了一个函数。我想在其中发送一个char指针,但它似乎没有修改它。我遇到的另一个问题是我的函数只存储了一些数据,所以如果数据很长,我的程序会崩溃。

2 个答案:

答案 0 :(得分:0)

我在这里看错了:

caracter

char&指针。通过将caracterchar一起使用,您试图访问printf("%s", caracter); 指针的地址,而不是指针所指向的内容。

将其更改为

lector

其次,while((strcpy(lector,getchar())) !='\n' && lector!=EOF) 在使用之前初始化为什么?见这里:

{{1}}

答案 1 :(得分:0)

这将代码简化为一个函数来捕获输入直到换行。内存分配在每个角色上。

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

char *generarCadena(char *);

int main(void){
    char *caracter=NULL;//so realloc will operate as malloc on first call
    caracter = generarCadena ( caracter);
    printf("%zu\n", sizeof(caracter));
    if ( caracter) {//something was input
        printf("%s\n", caracter);
        free ( caracter);
    }
    return 0;
}

char *generarCadena(char *scaneado){
    char *temp = NULL;
    int in = 0;
    size_t size = 0;

    while ( '\n' != ( in = getchar ( ))) {//loop until newline
        if ( NULL == ( temp = realloc ( scaneado, size + 2))) {//realloc for each character input and '\0'
            fprintf ( stderr, "realloc problem\n");
            return scaneado;
        }
        scaneado = temp;
        scaneado[size] = in;//set input
        scaneado[size + 1] = '\0';//terminate
        size++;
    }
    return scaneado;
}