0

I need to create a char array dynamically based on the pattern length, i.e., plen. However, when I do sizeof(table), I get 8. Why am I getting 8 instead of 3?

int main() {
    char *pattern = "aaa";
    int plen = strlen(pattern);
    char *table = new char[plen + 1];
    for(int i = 0; i < plen; i++) {
        table[i] = pattern[i];
    }
    cout << sizeof(table) << plen << table;
    return 0;
}

The output I get is 83aaa...: 8 for sizeof(table), 3 for plen and aaa for table, which has the stored value of pattern.

10
  • 1
    sizeof happens at compile time, based on the type. Commented Mar 14, 2014 at 19:17
  • well when i do strlen i get 3..since its a character array.but i dont know how it gets 8 when i do sizeof. Commented Mar 14, 2014 at 19:19
  • because table is a pointer and the size of a pointer is 8 byte on your system Commented Mar 14, 2014 at 19:20
  • If you are treating table like a string, make sure it is null terminated and then check length with strlen. Commented Mar 14, 2014 at 19:21
  • A pointer is not holding data, but pointing to an address where the data is. Commented Mar 14, 2014 at 19:22

2 Answers 2

2

It is because table is a pointer, not an array. And the size of a pointer in your architecture is 8 bytes.

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

1 Comment

so if i use char *table=new char[plen+1]; or int * t=new int[4]; and do a sizeof(t)or sizeof(table), i will get 8, since its a pointer.Well for a char *.. I will be doing strlen.I was just juggling around to see the difference
0

sizeof(expression) is just a syntactic alternative to sizeof(type of that expression).

In your example, sizeof(table) is just a syntactic alternative to sizeof(char*). The value of the pointer or the char it points to or the array it points to are never considered for the result, only the type.

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.