FinalDestiny
FinalDestiny

Reputation: 1188

Creating one array of strings in C fails, why?

I tried to create one array of strings in C. Here is the code:

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

int main()
{
    char *foo[100];
    strcpy(foo[0], "Testing this");
    printf("%s ", foo[0]);

    return 1;
}

But when I compile it, it simply breaks. No error, no nothing, it simply doesn't work and breaks. Any suggestion? When I tri char *foo[10] it works, but I can't work with just 10 strings

Upvotes: 0

Views: 164

Answers (5)

Srajal Tiwari
Srajal Tiwari

Reputation: 3

#include <stdlib.h>
#include <stdio.h>

int main(void){
    char *foo[100];
    foo[0] = malloc(13*(sizeof(char)));
    strcpy(foo[0], "Testing this");
    printf("%s ", foo[0]);

    return 0;
}

This is the corrected version of your code.

MISTAKE: not allocating enough memory for the string.

CORRECTION: using malloc to allocate 13 blocks of memory for the string.

Upvotes: 0

Eddie Paz
Eddie Paz

Reputation: 2241

You are creating an 100 pointers to point no where. As explained by David, you need to dynamically allocate the memory. However, you can also have the compiler do this for you if you know the size of the strings (or max):

// Create an array of 10 strings of size 100 and initialize them automatically
char foo[10][100] = {0};

// Now you can use it them and not worry about memory leaks
strcpy(foo[0], "text");

// Or use the safer version
strcpy_s(foo[0], 100, "text");

Upvotes: 1

David Pointer
David Pointer

Reputation: 935

Expanding upon other people's answers:

char *foo;

is a pointer to a character. It may be assigned the address of a single character or assigned the address of the first of a sequence of characters terminated by '\0'. It may also be assigned an address via malloc().

char foo[100];

is space for 100 characters or space for a string of up to 99 characters and a terminating '\0' character.

char *foo[100];

is 100 character pointers, i.e., 100 char *foo; types.

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612954

You allocated an array of pointers but did not allocate any memory for them to point to. You need to call malloc to allocate memory from the heap.

char *foo[100];
foo[0] = malloc(13);
strcpy(foo[0], "Testing this");

Naturally you would need to free the memory at some later date when you were finished with it.

Your code invokes what is known as undefined behavior. Basically anything can happen, including the code working as you intended. If the version with char *foo[10] works as you intended that's simply down to luck.

As an aside, your main() definition is wrong. It should be int main(void).

Upvotes: 4

Asaf
Asaf

Reputation: 4407

You're assigning an unallocated pointer. char *foo[100] is an array of 100 unallocated pointers, and they point to unknown locations in memory, ones which you can probably not access.

Upvotes: 1

Related Questions