Reputation: 59
Program for work with arrays in dynamic memory. Need equivalent for C. Can anybody help?
const int n = 6;
char **words = (char**) malloc(n *sizeof(char*));
for(int i = 0 ; i < n; i++)
words[i] = (char*)malloc( 50 * sizeof(int));
for(int i = 0; i < n; i++)
{
cin>>words[i];
}
cout<<endl;
for(int i = 0; i < n; i++)
{
if(words[i][0] == 'q')
cout<<words[i]<<endl;
}
Upvotes: 1
Views: 207
Reputation: 95
As you wish:
const int n = 6;
char **words = (char**) malloc(n *sizeof(char*));
int i = 0;
for( i= 0 ; i < n; i++)
{
words[i] = (char*)malloc( 50 * sizeof(char));
}
for(i = 0; i < n; i++)
{
scanf("%s", words[i]);
}
printf("\n");
for(i = 0; i < n; i++)
{
if(words[i][0] == 'q')
printf("%s\n", words[i]);
}
Upvotes: 0
Reputation: 126877
The only C++ parts there are cin
and cout
; you can change them easily:
cin>>words[i];
becomes
scanf("%s", words[i]);
or
gets(words[i]);
while
cout<<words[i]<<endl;
becomes
puts(words[i]);
By the way, in the cin
/scanf
/gets
you have a potential buffer overflow, since you are allocating space for 6 characters but you are accepting input of any length. You should do instead:
scanf("%6s", words[i]);
or (more maintainable, since it uses n
directly)
fgets(words[i], n, stdin);
(although this will include the trailing \n
in the string)
Upvotes: 6
Reputation: 27115
Use scanf("%s", &words[i])
to input data from stdin and printf("%s\n", words[i])
to output to stdout.
Upvotes: 1
Reputation: 681
The only C++ features you are using are cin and cout. replace cin>>words[i]
with gets(words[i])
and cout<<words[i]<<endl
with puts(words[i])
.
Upvotes: 2