Pointers to dynamic strings

0

-What I wanted to do, I could not implement it, is that when asking for a name and a surname to the user a priori we DO NOT KNOW what will be the stdin length that the user types. In the malloc line I put 10 to put as I could have put 20 but in fact I do not know how much will occupy the name and surname that I enter the user keyboard I do not know how to implement it in such a way that when you type a name and a surname calculate the length and then and reserve memory for that length to part also to reserve the memory just and necessary for what I type the user and not walk blind assuming that you enter a name and last name of 10,20,30 etc bytes

-As I did not go out, I did this that does not look like anything I wanted to do in the beginning and that even above I can not make it work the way I want to do it. I hope you have explained me clearly and thank you

  

First doubt, because the code does not work as it should? fault of the fgets?

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

int main(void){
    char *nombre,*nombre2;
    nombre=malloc(10*sizeof(char)); //reservo 10 bytes
    printf("Introduce tu nombre y apellido: ");

    fgets(nombre,9,stdin); //agrega NULL y \n si se ingresan menos caracteres
    if (nombre[strlen(nombre)-1] == '\n'){
        nombre[strlen(nombre)-1] = '
while(1):
    cadena=str(input("Introduce lo que quieras o exit para salir: "))

    if(cadena=="exit"):
        break
    print(cadena)
'; } printf("%s\n",nombre); long int longitud=(strlen(nombre)+1); //strlen no cuenta el NULL de final de cadena printf("%li\n",longitud); if(longitud>8){ nombre2=realloc(nombre,15*sizeof(char)); //reasigno 5 bytes printf("%s\n",nombre); free(nombre2); } free(nombre); return 0; }
  

Second doubt, would it be possible to implement it?

Regarding the idea if someone knows python the code that I want to implement in c would be something like this in python:

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

int main(void){
    char *nombre,*nombre2;
    nombre=malloc(10*sizeof(char)); //reservo 10 bytes
    printf("Introduce tu nombre y apellido: ");

    fgets(nombre,9,stdin); //agrega NULL y \n si se ingresan menos caracteres
    if (nombre[strlen(nombre)-1] == '\n'){
        nombre[strlen(nombre)-1] = '
while(1):
    cadena=str(input("Introduce lo que quieras o exit para salir: "))

    if(cadena=="exit"):
        break
    print(cadena)
'; } printf("%s\n",nombre); long int longitud=(strlen(nombre)+1); //strlen no cuenta el NULL de final de cadena printf("%li\n",longitud); if(longitud>8){ nombre2=realloc(nombre,15*sizeof(char)); //reasigno 5 bytes printf("%s\n",nombre); free(nombre2); } free(nombre); return 0; }
    
asked by eduu15 07.04.2018 в 00:49
source

2 answers

0

If your problem is that you want to read how many bytes you want from stdin , then I suggest you learn about the functions to request dynamic memory from the OS, this snippet is a modification of this answer :

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

#define MAX_MULT (120)
char *leer_stdin(void) {
  int chr = 0, mult = 0, len = 0; 
  char *_c = NULL;

  while (1) {
    chr = fgetc(stdin);

    if (chr == EOF || chr == '\n') /* Detente solo si terminamos o si es final de linea */
      break;

    if (mult >= len) { /* pide más memoria si es necesario. */
      char *tmp = realloc(_c, mult + MAX_MULT);
      if (!tmp) /* si fall al pedir memoria, entonces detente ahora */
        break;
      _c = tmp, mult += MAX_MULT;
    }

    _c[len++] = chr; /* finalmente asigna. */
  }

  if (len)
    _c[len] = 0; /* pon el caracter nulo al final si no es NULL nuestra cadena */
  return _c; /* finalmente, devuelvela. */
}
#undef MAX_MULT

The function that I put here, puts all the memory you need to read from stdin , after this, you must release it with free and follow the execution of your program.

In your second 'doubt' you mention:

  

Is it possible to make the idea?

C is a programming language, like any other can perform tasks within what can ..? What you propose? It's the simplest:

#include <string.h>

int main(void) {
  while (1) {
    printf("Escribe algo: ");
    char *t = leer_stdin();
    if (t) {
      printf("Escribiste: '%s'\n", t);
      if (0 == strcmp(t, "salir")) { 
        free(t); break;
      }
      free(t);
    }
  }
  return 0;
}

The above code will read a string and print its content, obtained from the leer_stdin() function and evaluate it against the string "salir" if they are equal (If it returns zero) , then for the execution of the program.

  

Note: if you are going to put both code snippets in the same file, be sure to put all the directives #include and then a forward declaration or the definition of the function leer_stdin() to work correctly.

Greetings!

    
answered by 07.04.2018 / 22:24
source
0

One solution is to create a static buffer that allows you to host all the data collected by the console and then create the pointer of the appropriate size and assign it the corresponding value:

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

#define TAMANIO_MAXIMO_BUFFER 255

int main(void){
    char buffer[TAMANIO_MAXIMO_BUFFER] = {'
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define TAMANIO_MAXIMO_BUFFER 254

int main(void){
    char *nombre = malloc((TAMANIO_MAXIMO_BUFFER+1)*sizeof(char));
    char *nombre2;

    //nombre=malloc(10*sizeof(char)); //reservo 10 bytes
    printf("Introduce tu nombre y apellido: ");
    fgets(nombre, TAMANIO_MAXIMO_BUFFER, stdin); //agrega NULL y \n si se ingresan menos caracteres

    if (nombre[strlen(nombre)-1] == '\n'){
        nombre[strlen(nombre)-1] = '
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define TAMANIO_MAXIMO_BUFFER 255

int main(void){
    char buffer[TAMANIO_MAXIMO_BUFFER] = {'
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define TAMANIO_MAXIMO_BUFFER 254

int main(void){
    char *nombre = malloc((TAMANIO_MAXIMO_BUFFER+1)*sizeof(char));
    char *nombre2;

    //nombre=malloc(10*sizeof(char)); //reservo 10 bytes
    printf("Introduce tu nombre y apellido: ");
    fgets(nombre, TAMANIO_MAXIMO_BUFFER, stdin); //agrega NULL y \n si se ingresan menos caracteres

    if (nombre[strlen(nombre)-1] == '\n'){
        nombre[strlen(nombre)-1] = '%pre%';
    }

    nombre2 = realloc(nombre, strlen(nombre)*sizeof(char));
    if (nombre2 != NULL){
        nombre = nombre2;
    } else {
        printf("ERROR, no se puede reasignar la memoria");
        exit(1);
    }

    printf("%s\n",nombre);

    long int longitud=(strlen(nombre)+1); //strlen no cuenta el NULL de final de cadena
    printf("%li\n",longitud);

     free(nombre);
     nombre = NULL; //siempre es bueno setear a NULL un puntero que no va a volver a ser usado
     free(nombre2);
     nombre2 = NULL;

    return 0;
}
'}; char *nombre; //nombre=malloc(10*sizeof(char)); //reservo 10 bytes printf("Introduce tu nombre y apellido: "); fgets(buffer, TAMANIO_MAXIMO_BUFFER, stdin); //agrega NULL y \n si se ingresan menos caracteres if (buffer[strlen(buffer)-1] == '\n'){ buffer[strlen(buffer)-1] = '%pre%'; } nombre = malloc(strlen(buffer)*sizeof(char)); //reservo el tamaño necesario strcpy(nombre, buffer); //copio al puntero nombre el nombre recibido printf("%s\n",nombre); long int longitud=(strlen(nombre)+1); //strlen no cuenta el NULL de final de cadena printf("%li\n",longitud); free(nombre); nombre = NULL; //siempre es bueno setear a NULL un puntero que no va a volver a ser usado return 0; }
'; } nombre2 = realloc(nombre, strlen(nombre)*sizeof(char)); if (nombre2 != NULL){ nombre = nombre2; } else { printf("ERROR, no se puede reasignar la memoria"); exit(1); } printf("%s\n",nombre); long int longitud=(strlen(nombre)+1); //strlen no cuenta el NULL de final de cadena printf("%li\n",longitud); free(nombre); nombre = NULL; //siempre es bueno setear a NULL un puntero que no va a volver a ser usado free(nombre2); nombre2 = NULL; return 0; }
'}; char *nombre; //nombre=malloc(10*sizeof(char)); //reservo 10 bytes printf("Introduce tu nombre y apellido: "); fgets(buffer, TAMANIO_MAXIMO_BUFFER, stdin); //agrega NULL y \n si se ingresan menos caracteres if (buffer[strlen(buffer)-1] == '\n'){ buffer[strlen(buffer)-1] = '%pre%'; } nombre = malloc(strlen(buffer)*sizeof(char)); //reservo el tamaño necesario strcpy(nombre, buffer); //copio al puntero nombre el nombre recibido printf("%s\n",nombre); long int longitud=(strlen(nombre)+1); //strlen no cuenta el NULL de final de cadena printf("%li\n",longitud); free(nombre); nombre = NULL; //siempre es bueno setear a NULL un puntero que no va a volver a ser usado return 0; }

If you want to do it whole with dynamic memory you can do something like this:

%pre%     
answered by 08.04.2018 в 13:32