0

i wish to store n number of words to an array. I used pointer in the following code to do that .But the problem is that once all words are read the words are not able to print.

please provide any solution.

#include <stdio.h>
#include <stdlib.h>

int main() {

    char buff[10];
    int i,T;
    printf("Enter the  no.of words:");
    scanf("%d",&T);

    char **word= malloc(10*T);  
    printf("Enter the words:\n");
    for(i=0;i<T ;i++){
        scanf("%s",buff);
        word[i]= malloc(sizeof(char)*10);
        word[i]=buff;
        printf("u entered %s\n",word[i]);
        if(i>0)
            printf("u entered %s\n",word[i-1]);
    }

    printf("Entered words are:\n");
    for(i=0;i<T ;i++)
        printf("%s\n",word[i]);


}
1
  • The problem is you are storing the same buff pointer to each array element. That obviously means they all contain the same value and also causes a memory leak as the malloc buffer is lost. Use strcpy or strdup. Commented Apr 24, 2017 at 3:43

1 Answer 1

4

You need to allocate size of char * -

char **word= malloc(sizeof(char *)*T); 

And to copy string you need to use strcpy. So instead of this -

word[i]=buff;          // 1

use this -

strcpy(word[i],buff);         // include string.h header

By 1. you point to buff using a pointer but the value stored in buff changes. So value to which all pointers point is same and you get all same output i.e the most recent value stored in buff.

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

1 Comment

@kilowatt glad it hlped.

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.