0

How to define a variable using another variable.Actually I want a whole string but that string should contain data from another variable.

#include <stdio.h> char *Data1 = "23"; char *Data2 = "267"; char *Data = ("www.mywebsite.com?c=%s&v=%s", Data1, Data2); int main() { printf(Data); return 0; } 
1
  • 1
    Please read the manual pages. Please read about the comma operator Commented Jan 15, 2017 at 8:22

2 Answers 2

3

You can define an array and make use of sprintf()/snprintf() to generate the final string.

Something like

char final[128] = {0}; //128 is arbitrary value int data1 = 23; //no need to be string for integer value int data2 = 267; snprintf(final, 128, "www.mywebsite.com?c=%d&v=%d", data1, data2); 

That said, printf(Data); is very invalid. You either

  • use the proper format specifier, like printf("%s", final);
  • use puts(final);
Sign up to request clarification or add additional context in comments.

3 Comments

how do i store the output of statment snprintf(final, 128, "www.mywebsite.com?c=%d&v=%d", data1, data2); in one variable.I want output as a whole string.
@bhagyakathole Did you read the linked manual page? It is stored into final.
Is there any another solution for this statement snprintf(final, 128, "www.mywebsite.com?c=%d&v=%d", data1, data2);?my compiler is showing an error for this statement.
0

You can use snprintf

First define a MAX_LEN and a buffer

#define MAX_LEN 1000 char Data[MAX_LEN + 1] = ""; 

then use snprintf to fill in all strings:

snprintf( Data, sizeof(Data), "www.mywebsite.com?c=%s&v=%s", Data1, Data2); 

5 Comments

1) why MAX_LEN+1 ? 2) you missed passing the size.
@SouravGhosh about 1) it's called LEN, and so the size is +1
Sorry, but I still did not get. sprintf() writes at most n so why the extra byte needed?
@SouravGhosh is right: "The functions snprintf() and vsnprintf() write at most size bytes (including the terminating null byte ('\0')) to str."
it's just how I call the name of the constant - nothing to do with the snprintf, usually MAX_LEN (strlen) doesn't include the NUL character, whereas MAX_SIZE (sizeof) does.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.