search
Log In
0 votes
133 views

This code executes successfully

int main() {

char str[20];

gets(str);

puts(str);

return 0;

}

whereas the below code gives runtime error

int main() {

char *str;

gets(str);

puts(str);

return 0;

}

why so?

in Programming 133 views
1
you are not giving the size of str and gets() needs some size to do. In your first program, you have specified the size of str that's why it is not giving any error.
0
well I think in first case you have "reserved" the enough memory space to store 20 characters beforehand (a string longer than that might give runtime error) while the second causes segmentation fault for not having done the same.
0
@pankaj_vir even scanf needs a size? so does that mean we can never get a string from input console if its declared as char* ?
1
@Kiran Karwa, we need the size of string for the input.if its declared as char* then we need to use dynamic memory.
1
@Kiran Karwa,

#include<stdio.h>
#include<stdlib.h>
int main() {
  char str[20];
char *ptr;
int n;
//case 1
printf("Input a string");
gets(str);
puts(str);

//case 2
printf("Enter the size of the string");
scanf("%d",&n);
ptr=(char *)malloc(n*sizeof(char));
ptr="Hope is the bird with Feathers";
printf("%s",ptr);
free(ptr);
return 0;
}

Please kindly execute this code snippet. I hope you'll understand the difference between character array and pointer.

Please log in or register to answer this question.

Related questions

0 votes
1 answer
1
647 views
#include<iostream> using namespace std; int i=0; void a() { i+=1; cout<<i<< ".hello"<<endl; a(); } int main() { a(); } For this above code the output is only upto → 64891.Hello Does this mean that that the stack can hold only 64891 recursive calls? (I am using dev c++)
asked Jun 2, 2019 in Programming Hirak 647 views
0 votes
1 answer
2
920 views
#include<stdio.h> #include<stdlib.h> int main(void) { int maxLineCount = 500, maxCharCount = 500, index, j, count; char *line = NULL; size_t size; char *a[maxLineCount]; for (index = 0; index < maxLineCount; index++) a[index] = (char *)malloc(maxCharCount * ... of the code is doing. suppose we have 3 string given as input in 3 different lines then how can we access each character of the string?
asked Jun 1, 2019 in Programming Satbir 920 views
1 vote
1 answer
3
384 views
Implement Linked list using stack.
asked May 19, 2019 in Programming shraddha priya 384 views
2 votes
2 answers
4
302 views
Can someone explain the output of this code? and what (char*) is doing actually? #include<stdio.h> struct Ournode{ char x, y, z; }; int main() { struct Ournode p={'1', '0', 'a'+2}; struct Ournode *q=&p; printf("%c, %c", '*((char*)q+1)', '*((char*)q+2)'); return 0; }
asked May 13, 2019 in Programming srestha 302 views
...