简体   繁体   中英

How to create an uninitialised array of strings in C?

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM