Get the size of Data pointed by a list of pointers



  • I have this code:

    @char * str1 = "hello world !";

    QList<char *> *list = new QList<char *>;
    list->append(str1);
    
    qDebug()<<list->at(0);
    char *tmp = list->at(0);
    qDebug()<<sizeof(tmp);@
    

    the output is:

    bq. hello world !
    8

    where 8 is the size of the pointer tmp, how could I get the size of data pointed by tmp ??



  • Dunno why you still use annoying C style strings but you just need to use the usual strlen function to get it:
    @
    char * str1 = "hello world !";

        QList<char *> *list = new QList<char *>;
        list->append(str1);
     
        qDebug()<<list->at(0);
        char *tmp = list->at(0);
        qDebug()<<sizeof(tmp);
    

    char *pEnd;
    for (pEnd = tmp; *pEnd !='\0'; pEnd++)
    continue;
    qDebug()<< pEnd - tmp;
    @

    But it would be easier (even if slower) to use QString:
    @
    char * str1 = "hello world !";

        QList<char *> *list = new QList<char *>;
        list->append(str1);
     
        qDebug()<<list->at(0);
        char *tmp = list->at(0);
        qDebug()<<sizeof(tmp);
        qDebug()<<QString(tmp).size();
    

    @



  • In C/C++ it generally is not possible to know the size of a memory buffer (array) only from the pointer. The pointer really is only the address where the buffer/array starts. Not more! If the array is of type char and also is guaranteed to be NULL-terminated, then (and only then) one could use strlen(). And even then it only gives the length of the string (excluding NULL terminator), not the buffer size. That's why we often pass a pointer plus a length, instead of only the pointer. It of course would be more convenient to use QString or QByteArray.


  • Moderators

    One additional remark, this will work only for strings as defined above. There is no general answer to your question. In most cases you cannot do that, because the pointer simply points to the start location of memory. It does not know anything about the end of the allocated memory.



  • @VRonin:
    Thank you, it worked for me
    I am using C style because this is not the original code, I am trying to proof a concept where char * is a must.



  • [quote author="ahmed kato" date="1357672414"]@VRonin:
    Thank you, it worked for me
    I am using C style because this is not the original code, I am trying to proof a concept where char * is a must.[/quote]

    Keep in mind strlen() only gives you the number of non-NULL char's before the first NULL char.

    That's fine if you know for sure that all char-pointers in your QList will point to memory containing a NULL-terminated string. In any other case using strlen() is wrong - it can even be dangerous!

    (I say this because you originally asked for "the size of Data", not for "the length of a the String")


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.