-1

I'm trying to create an array of strings using calloc method and I'm getting quite a lot many errors.

int main() {
    int T,i;
    char *w;
    char **s;

    w=(char*)calloc(100,sizeof(char));
    scanf("%d",&T);
    s=(char**)calloc(T,sizeof(char));
    s=(char*)calloc(100,sizeof(char));
    for(i=0;i<T;i++)
    { 
      scanf("%s",w);
      s[i]=w;
    }   
}

In the above code T is the number of strings and w is the maximum size of the string. Please shed some light on as to how I should be declaring string arrays dynamically and statically.

4
  • 1
    calloc(T,sizeof(char)) ==> calloc(T,sizeof(char*)). But anyway, you immediately overwrite that pointer. Commented Oct 17, 2020 at 16:52
  • @WeatherVane But I am still getting an error Commented Oct 17, 2020 at 16:54
  • 1
    Please see this answer. Commented Oct 17, 2020 at 16:55
  • 1
    1) Declare and array of strings statically: char[NSTRINGS][STRINGLEN]. 2) Allocate an array of strings dynamically: calloc(NSTRINGS,sizeof(char*)). 3) Allocate one string dynamically: calloc(STRINGLEN,sizeof(char)) Commented Oct 17, 2020 at 17:01

1 Answer 1

1

If your array stores string pointers, a new string must be allocated for each of them :

int main() {
    int arraySize,i;
    char *str;
    char **arrayOfPtr;
    scanf("%d", &arraySize);
    arrayOfPtr = (char**)calloc(arraySize,sizeof(char*));
    
    for(i=0;i<arraySize;i++)
    {  
      str =(char*)calloc(100,sizeof(char)); //<== string allocation
      scanf("%s", str);
      arrayOfPtr[i]= str;
    } 

And you must free strings and array separately because the string memory is not that of the array :

    for (i=0;i<arraySize;i++) free(arrayOfPtr[i]);
    free(arrayOfPtr);
}
Sign up to request clarification or add additional context in comments.

Comments

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.