1

/* program to accept and print 5 strings using pointers */

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define SIZE 100

int main()
{
    char **s;
    int i;
    s = (char *)malloc(sizeof(char)*5);
    for(i=0;i<5;i++)
    {
        *(s+i) = (char *)malloc(sizeof(char)*SIZE);
    }

    printf("enter 5 strigs\n");
    for(i = 0;i<5;i++)
    {
       fgets((s+i),SIZE,stdin);
    }
    //printing the strings
    for(i = 0;i<5;i++)
    {
            puts((s+i));
    }
     return 0;
  }

This program accepts 5 strings from keyboard and prints on screen.It works properly but shows many warnings.Is there any other ways to do same operation(using pointers only).please suggest me.

vinaykp
  • 539
  • 2
  • 5
  • 16

2 Answers2

0

The biggest issue in your code is that you do not allocate enough memory to s:

s = malloc(sizeof(char*)*5);
//                    ^
// Add an asterisk here

Otherwise, it's undefined behavior.

Second biggest is that you are not freeing any of the memory that you allocated. This is a memory leak. To do it properly you need a loop that calls free on every element of s, and then on the s itself:

for(i = 0;i<5;i++) {
    free(s[i]);
}
free(s);

Finally, you should not be casting the results of malloc.

As a point for style, consider defining a constant for the number of elements in s, in the same way that you defined SIZE instead of using 100 directly. It may also make sense to switch to array-style dereference, rather than doing pointer arithmetic manually, i.e. puts(s[i]); instead of puts((s+i));

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • thanks...code worked.. what what happens if we cast the results of malloc? how to free memory? is it enough to give free(s) at the end? – vinaykp May 03 '14 at 12:47
0

int main() {

char **s;

int i;
s = (char **)malloc(sizeof(char*)*5); //double pointer (char**)
for(i=0;i<5;i++)
{
    *(s+i) = (char *)malloc(sizeof(char)*SIZE); 
}

printf("enter 5 strigs\n");
for(i = 0;i<5;i++)
{
   fgets(*(s+i),SIZE,stdin); // first location *(s+0)
}
//printing the strings
for(i = 0;i<5;i++)
{
        puts(*(s+i)); // first location *(s+0)
}
 return 0;

}

Rocoder
  • 1,083
  • 2
  • 15
  • 26