Susan
Susan

Reputation: 301

C, array, how to make use of strlen

i am writing a simple program and would like to use the strlen function to get the size of the string in question.

Then i would like to create an array for example testarray[strlen(somestring)];

But it cannot compile, the error says "error: variable-sized object may not be initialized".

However, the length of that string will not change so i guess i have to tell my machine that somehow.

I have only access to these headers.

stdio.h string.h

Would be great if somebody could drop some knowledge bombs. :)

edit: I was wrong testarray[strlen(somestring)]; can compile but testarray[strlen(somestring)] = {}; cannot. With testarray[strlen(somestring)]; i have garbage if i try to use it.

Thanks guys, it is working now with memset!

Upvotes: 1

Views: 6547

Answers (4)

Batiment
Batiment

Reputation: 1

I hope this helps

#include <stdio.h>
#include <string.h>

int main(int argc, const char * argv[])
{
    char array[256];
    printf ("Enter a sentence: ");
    fgets(array, 256, stdin);
    printf ("The sentence entered is %zu characters long.\n", strlen(array));
    return 0;
}

Upvotes: 0

Sankar Mani
Sankar Mani

Reputation: 178

testarray[strlen(somestring)] = {};

The above initialization not possible. Because the string size will be calculated dynamically(May vary). For static array initialization we should provide the exact size of the array.

You can initialize your dynamic array by using 'memset'.

Upvotes: 0

Jason
Jason

Reputation: 1632

You need to initialize the memory in temp to 0. This is what the empty brackets {} did in your original code. Either use memset

memset(temp, 0, sizeof(temp));

Or a for loop (since you don't have malloc/free you may not have memset).

int length = sizeof(temp);
int i;
for (i = 0; i < length; ++i)
{
   temp[i] = 0;
}

Upvotes: 0

paulsm4
paulsm4

Reputation: 121629

Your best bet is to use "malloc()"

char *testarray = (char *)malloc(strlen(somestring)+1);

If you were programming in C++, I'd encourage you to use a vector<>.

C99 introduced "variable length arrays", but they're not portable to all C compilers. Personally, I'd discourage you from using them.

Which leaves you with "malloc ()" ;)

And, nhahtdh is quite right, be sure you always do a corresponding "free()".

Upvotes: 2

Related Questions