The Gateway to Computer Science Excellence
0 votes
73 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 by Active (1.1k points) | 73 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
3
Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,737 questions
57,297 answers
198,265 comments
104,978 users