简体   繁体   中英

C Reading user entered data

I'm trying to write a simple program that reads user entered strings into an array of pointers. The reading goes fine, however when I want to add an extra parameter to my method in order to save how many Strings I actually read, it stops working. The compiler isn't very helpfull so I decided to take my problem here.

Actual code:

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

void read(char**, int *);
void write(char**);

int main() {
    int amount = 0;
    int * amount_p = &amount;
    char *pt_p[1000];
    read(pt_p,amount_p);
    write(pt_p);
}


void read(char ** pt, int * amount) {

    char  stop[] = "STOP";
    char* woord;
    int i = 0;

    printf("Enter a word: ");
    scanf("%70s", woord);
    pt[i] = malloc(sizeof(char)*(strlen(woord)+1));
    pt[i] = strcpy(pt[i], woord);

    i++;

    while(strcmp(stop,pt[i-1]) != 0) {
          printf("Enter a word: ");
          scanf("%70s", woord);
          pt[i] = malloc((strlen(woord)+1)*sizeof(char));
          pt[i] = strcpy(pt[i], woord);
        i++;    
    }
    *amount = i;

}

void write(char ** pt) {
    int i = 0;
    char  stop[] = "STOP";
    while(strcmp(stop,pt[i]) != 0 ) {       
        printf("pt[%d]-> %s",i,pt[i]);
        printf("X \n");
        i++;
    }

}

you need to allocate some space where you can enter the string

char* woord; is just declaring a pointer that points nowhere in particular.

instead declare it as

char woord[128];

to allocate 128 bytes on the stack for your input.

also use fgets() instead of scanf() to read strings, that way you can prevent user from entering a too large string.

if ( fgets( woord, sizeof(wooord), stdin ) != NULL )
{
  char* p = strchr( woord, '\n' );
  if (p != NULL ) 
  {
    *p = '\0';
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM