I like to know that I have data which are in pair of two strings so there are a list of pair of two strings. like
{{"<html","</html>"},{"<head","</head>"}}
So I want to define pointer variable as is array of pointers to pointers
so pointers will be pointing to pointers that points to strings (should be char *
) like string <html
is pointed by pointer *tags_1[0]
and </html>
is pointed to by what, I may be completely wrong? this is a question. But first I like to know how to define or construct this array of pointers to pointers like initialiing it with above {{"<html","</html>"},{...}}
for tags_1
I tried like char **tags_1[2]={{"<html","</html>"},{"<head","</head>"}};
but this obviously wrong but I can do this if I have array of pointers static char *tags[] = {"<html","<head","<body","<div","<h1","<h2","<h3","<h4","<h5","<br", "<span","<input","<footer","<section","<table","<tr","<td","<a","<button","<end"};
so my question is how to define like assigning initialized values to array of pointers to pointers then how to use them especially comparing string <html
and </html>
indexed elements with strncmp
of array of pointers to pointers and printf
and assigning character to each indexed of string (char *). Can anyone please tell me this
CodePudding user response:
A concise way to allocate is to use a Pointer-to-Array-of char*[2]
, e.g.
char *(*tags)[2];
That way you can use a single allocation for however many pairs you have, and easily realloc
if you need more. A short example would be:
#include <stdio.h>
#include <stdlib.h>
int main (void) {
char *(*tags)[2] = malloc (2 * sizeof *tags);
tags[0][0] = "<html";
tags[0][1] = "</html>";
tags[1][0] = "<head";
tags[1][1] = "</head>";
for (int i = 0; i < 2; i ) {
for (int j = 0; j < 2; j )
printf (" %s", tags[i][j]);
putchar ('\n');
}
free (tags);
}
Example Use/Output
$ ./bin/ptr2arrcharstar
<html </html>
<head </head>
Let me know if you have further questions.
CodePudding user response:
For this you don't need an array of pointers to pointers.
What you need is an array of array of char-pointers. It looks like:
const char* tags[][2] = {{"<html","</html>"},{"<head","</head>"}};
Now you can do stuff like:
printf("%s\n", tags[0][0]); // prints <html
printf("%s\n", tags[1][1]); // prints </head>
and
char str[] = "some_text";
if (strcmp(str, tags[1][0]) == 0) // Check if str equals <head
{
// Match
}