0

Here is my code

char* a[10]; a[0]="'example'"; char* p; p=strstr(a[0],"'"); 

I know if strstr can find the ' it returns a pointer which points to first character which is '. I want to take the value between two ' and save it in a[1]. how should I do that? As a result a[1] is "example".

2
  • 1
    if (p) a[1] = p + 1; makes a[1] point to just after the first '. You need some way to find the next ' inside that string. Commented Aug 6, 2012 at 21:53
  • Homework? (blah blah total rubbish waste of my time and everyone elses extra characters for crazy SO developers) Commented Aug 6, 2012 at 22:00

2 Answers 2

2

strchr() seems a more appropriate choice that strstr().

Use the result of first strchr(), + 1, as the argument to a subsequent strchr() and then malloc() and strcpy() or sprintf() into a[1]:

#include <stdio.h> #include <string.h> #include <stdlib.h> int main() { char* a[10]; char* p; a[0] = "'example'"; p = strchr(a[0], '\''); if (p) { char* q = strchr(++p, '\''); if (q) { a[1] = malloc((q - p) + 1); if (a[1]) { sprintf(a[1], "%.*s", q - p, p); printf("[%s]\n", a[1]); } } } return 0; } 

Storing pointers to string literals and malloc() data into the same array seems a dangerous thing to do. You must free() dynamically allocated memory, but only dynamically allocated memory. The code will need to know what elements in a are pointing at dynamically allocated memory, and must be free()d, and those that are not.

Initialise a to all NULLs, so it is known what elements are populated:

char* a[10] = { NULL }; 

and calling free() on a NULL pointer is safe (does nothing).

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

1 Comment

What I need is strchr(). Thanks a lot.
1

Just find the next occurrence of ' and copy the substring:

char* a[10]; a[0]="'example'"; char* p, *q; p=strstr(a[0],"'"); if (p) { q = strstr(p+1, "'"); if (q) { size_t len = (size_t)(q - p); char *sub = malloc(len + 2); if (!sub) { /* Oops */ exit(EXIT_FAILURE); /* Something more sensible rather */ } memcpy(sub, p, len+1); sub[len+1] = 0; a[1] = sub; } else { a[1] = NULL; } } else { a[1] = NULL; } 

Note that in this case, it would be better to use strchr to find the single character.

2 Comments

strncpy() is a dangerous function. In this case, since you know exactly how many bytes you want to copy, memcpy() would be cleaner.
Right, memcpy is better. Although when you know exactly how many bytes to copy, that is the situation where strncpy is safe too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.