0

I have a char array contains string separated by null. I have the indexes for the strings present in the char aarray. How to read string from this char array using index and are separated by null.

e.g. I have following char array,

char *buf = ['\0', 'b', 'c', 's', '\0', 'n', 'e', 'w', '\0', 'n', 'x', 't', '\0'];

I have the indexes for these strings e.g index 1 for bcs string index 5 for new string index 9 for nxt string

How read these string using index from this char array?

1
  • 1
    buf + index gives you the string. Like buf + 1 for the first string. Commented Mar 12, 2016 at 10:01

3 Answers 3

1

Sorry for the simple question, I got the answer, We can get string from char array as follows: - Get the address of index of which string you want to get - Print the string

char* str = &buf[index];
if(str)
printf("string is : %s\n", str);
Sign up to request clarification or add additional context in comments.

2 Comments

str cannot ever be NULL so the test is obsolete.
Or char* str = buf + index;, as suggested to you in a comment by @Selçuk Cihan.
1

A more general approach would be to go through buf until you have printed all strings, i.e., without using indexes.

The problem is then how to identify the end of the (used part of) the buffer. A general trick for that is to terminate the buffer with an extra null character. The following demonstrates this:

char buf[] = {'\0', 'b', 'c', 's', '\0', 'n', 'e', 'w', '\0', 'n', 'x', 't', '\0', '\0'};

void f(void)
{
    char *s= buf;
    do {
        if (*s==0) {
            if (*(s+1)==0) break;
            s++;
        }
        puts(s);
        while (*s) s++;
    } while(1);
}

Comments

0

Here is how you do it.I didn't do any safety check though, the code just shows how to read strings from character array separated by null terminator.And whenever you are assigning multiple values to an array use this brackets [] rather use curly braces {}

#include <stdio.h>
int main(void) {
   char buf[] = {'\0', 'b', 'c', 's', '\0', 'n', 'e', 'w', '\0', 'n', 'x', 't', '\0'};
   int indx = 0;
   printf("Which index to read from:");
   scanf("%d", &indx);
   for(int i = indx; buf[i] != '\0'; i++){
    printf("%c", buf[i]);
  }
}

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.