0
#include<stdio.h>

int main(){
  char *q;
  int i=0;
  do{
    *(q+i)=getchar();
    i++;
  }while(*(q+i)!=48);

  int j=0;

  for(;j<i;j++)
    printf("%c",*(q+j));
}

I try to use in this way. I could compile. However ıt does not work . My aim is that I wanna acquire char array (unlimited or limit will be defined by the user) What should I do?

2
  • 1
    You didn't allocate any space for q Commented Oct 9, 2014 at 14:06
  • undefined behavior is not the way to go, and for such a small program, a char[] will do. Avoid dynamic memory when you can, it's slower and adds complexity. Bugs like complexity Commented Oct 9, 2014 at 14:16

2 Answers 2

2

You should read a book on C.

You're just writing into random memory, causing undefined behavior.

You must allocate memory, you can't just write through a non-initialized pointer!

For instance, make it:

char buffer[1024], *q = buffer;

Then make sure you don't overstep inside the loop, of course.

Also, there's no point in writing the access as *(p + i), when p[i] means the exact same thing and is much easier to read.

Finally, remember that technically getchar() returns int, since it can return EOF which is not a character.

Sign up to request clarification or add additional context in comments.

1 Comment

@eznme Could you please clarify?
0

1st allocate memory for your pointer *q

  include<stdio.h>

  int main()
 {
    int a;

    char b[100];
    int i=0;
    char *p=b;
   while((a=getchar())!=EOF)
 {
    p[i++]=a;
 }
 p[i+1]='\0';
printf("%s",b);

}

Also you can try heap memory allocation

char *p=(char*)malloc(40);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.