PeterPan
PeterPan

Reputation: 744

Arrays with several sentences in C

How can I do that? In Swift 2 I'd do something like that:

let test = [
    "I'm a sentence.",
    "Me too.",
    "What am I?",
    "I'm whatever"
]

print(test[1])

How do I do the same in C?

I tried the following:

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

int main()
{
 const char strings[] = {
        "I'm a sentence.",
        "Me too.",
        "What am I?",
        "I'm whatever"
  };
  printf("%s", strings[1]);
  return 0;
}

Upvotes: 1

Views: 2769

Answers (2)

ThunderWiring
ThunderWiring

Reputation: 738

Alright...So first of all, understand what is going on here:

"me too" is an array of chars by itself, and so each of the sentences you put. Also, a char* points to the first char in the sentence.

Your Problem: you did not create an array that holds on all the sentences(aka points at each first char of each sentence), instead you defined char strings[] which is an array of chars, AKA points to only one sentence(char*, remember?)

However, instead you should declare an array of char*, so you'll have this:

                 'o' <- 0X6
                 'o' <- 0X5
                 't' <- 0X4
                 ' ' <- 0X3
                 'e' <- 0X2
                 'm' <- 0X1
                  ^
                  |  . . .
                ----------------
char* arr[]:    | 0x1 |   |   |
                ----------------

Upvotes: 1

amdixon
amdixon

Reputation: 3833

example

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

int main()
{
  const char *strings[] = {
        "I'm a sentence.",
        "Me too.",
        "What am I?",
        "I'm whatever"
  };
  printf("strings[1]: %s\n", strings[1]);
  return 0;
}

output

$ ./test 
strings[1]: Me too.

Upvotes: 6

Related Questions