0

I'm running a program to read in a string in C. I'm having a weird problem with storing the string. My code is:

void getarray(char *text){
  char a, *p;
  int b = 1;

  p = text;
  scanf("%c", &a);
  if(a == '\n'){
    *p = '\0';
    return;
  }

  while(a != '\n'){
    *(p+b-1) = a;
    p = realloc(p, sizeof(char)*(b+1));
    b++;
    scanf("%c", &a);
  }
  *(p+b) = '\0';
}

So this reads in the characters properly, but when it reaches the end of the string, it does nothing, rather than continuing past the while loop. If I print out a as the last command in the while loop, when it reaches the end of the string it prints a blank space, but the program doesn't leave the loop.

Any help appreciated, thanks!

mcw
  • 465
  • 1
  • 4
  • 14
  • `Char* p` is local to `void getarray()`. – Shravan40 Feb 18 '14 at 05:14
  • I am calling it by defining `char *text`, then `text = (char *) malloc(sizeof(char));`, then calling `getarray(text)` – mcw Feb 18 '14 at 05:17
  • 1
    Possible duplicate - http://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-buffer – Anish Ramaswamy Feb 18 '14 at 05:24
  • Although your code has other issues, what you have described doesn't seem to be one of them. – Ja͢ck Feb 18 '14 at 05:48
  • Just something I noticed, if `p` in your `realloc` call is not already pointing to memory initialized by a previous call to `realloc`, `calloc` or `malloc`, and if `p` is not NULL, it results in undefined behavior. – Anish Ramaswamy Feb 19 '14 at 00:26

3 Answers3

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

void getarray(char **text){
    char a, *p=malloc(1);
    int b = 1;

    while(1==scanf("%c", &a) && a != '\n'){
        p = realloc(p, b+1);
        p[b++ - 1] = a;
    }
    p[b-1] = '\0';
    *text = p;
}

int main(){
    char *text;
    getarray(&text);
    printf("%s\n", text);
    free(text);
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
0

you can use getchar() function instead scanf(). It accept string until user Hit ENTER. Please find getarray() function

void getarray(char *text)
{
  int a;
  char *p;
  int b = 1;
  p = text;
  a = getchar();   
  if(a == '\n'){
    *p = '\0';
    return;
  }

  while(a != '\n')
  {
    *(p+b-1) = a;
    p = realloc(p, sizeof(char)*(b+1));
    b++;
    a = getchar(); 
  }
  *(p+b) = '\0';
}
Jayesh Bhoi
  • 24,694
  • 15
  • 58
  • 73
0

Your p = realloc(p, sizeof(char)*(b+1)) line is creating problem.

Replace line p=text by p= malloc(1);

quetzalcoatl
  • 32,194
  • 8
  • 68
  • 107
Amit
  • 81
  • 5