Okay so as you can see I have a problem. I am trying to create an array of string in C with a function called tab_string. If you try to run the following code you will see that I have a segfault with the test number two and I don't know why because the first test work. Thanks in advance
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NB_STRING 2
void create_tab_string(char chaine[], char*** p_tab_string) {
char test[] = "Hey";
char test2[] = "blabla";
// Allocation
*p_tab_string = (char **)(malloc(NB_STRING*sizeof(char*)));
// Test
*p_tab_string[0] = test;
printf("%s \n", *p_tab_string[0]);
// Test 2 ERROR ?????
*p_tab_string[1] = test2;
printf("I have the second string \n");
printf("%s \n", *p_tab_string[1]);
}
int main() {
int i;
char string_test[] = "I am a test";
char **tab_string;
create_tab_string(string_test, &tab_string);
for(i = 0; i < NB_STRING; i++)
printf("%s \n", tab_string[i]);
return 0;
}
You have a problem of operator precedence.
You need to use:
(*p_tab_string)[1]
and not *p_tab_string[1].
Also, as written in the comments your test strings are local into function, not available outside the function scope. You need to either duplicate them or use pointers.
Your function should be
void create_tab_string(char chaine[], char*** p_tab_string) {
char *test = "Hey";
char *test2= "blabla";
// Allocation
*p_tab_string = malloc(NB_STRING*sizeof(char*));
// Test
(*p_tab_string)[0] = test;
printf("%s \n", (*p_tab_string)[0]);
(*p_tab_string)[1] = test2;
printf("I have the second string \n");
printf("%s \n", (*p_tab_string)[1]);
}
First of all address of your test c-strings (arrays) are local to function and not accessible outside.
As you can see I changed them to simple pointers to string literals, so the strings literals are accessible outside the function.
Second thing are the way you are dereferencing your pointers.
Using *p_tab_string[1] you are dereferencing the second item of p_tab_string that does not exists.
Using (*p_tab_string)[1] you can dereference the second item of thing pointed by *p_tab_string, that is tab_string declare into main
Related
I have been trying to solve this issue for whole day, and could not do it on my own. Searching the internet didn't help me solve it either
So, this the function prototype:
void invert(char **arr, int n);
First argument is an array of strings, and the second one is number of strings in an array.
This is my code:
#include <stdio.h>
#include <string.h>
void invert(char** arr, int n)
{
int i, j, len;
for(j=0;j<n;j++)
{
len=strlen(arr[j]);
for(i=0;i<len/2;i++)
{
char tmp = arr[j][i];
arr[j][i] = arr[j][len - i - 1];
arr[j][len - i - 1] = tmp;
}
}
}
int main()
{
int n=3, i;
char **arr;
arr[0]="John";
arr[1]="Doe";
arr[2]="Programmer";
invert(arr, n);
for(i=0;i<3;i++)
{
printf("%s ",arr[i]);
}
}
The code breaks when it reaches the line:
arr[j][i] = arr[j][len - i - 1];
and I can't figure out why.
The function receives an array of strings perfectly (tested it with some printf statements for characters of specific strings), and the char tmp succesfully recieves a correct character, but the program crashed when it reaches the line mentioned earlier. Printf statements after that line don't work.
Did I miss anything? Can someone explain what am I doing wrong? Thank you!
For starters this code snippet
char **arr;
arr[0]="John";
arr[1]="Doe";
arr[2]="Programmer";
invokes undefined behavior because the pointer arr is uninitialized and has an indeterminate value.
Moreover this approach in any case is wrong because you may not change string literals.
What you need is to declare a two-dimensional array as for example
enum { N = 11 };
//...
char arr[3][N] =
{
"John", "Doe", "Programmer"
};
In this case the function declaration will look like
void invert( char arr[][N], int n );
The enumeration must be declared before the function declaration.
Instead of the two-dimensional array you could declare an array of pointers like
char s1[] = "John";
char s2[] = "Doe";
char s3[] = "Programmer";
char * arr[3] = { s1, s2, s3 };
In this case the function declaration may be as shown in your question
void invert(char** arr, int n)
So what you need to do with minimal changes is to substitute this code snippet
char **arr;
arr[0]="John";
arr[1]="Doe";
arr[2]="Programmer";
for this code snippet
char s1[] = "John";
char s2[] = "Doe";
char s3[] = "Programmer";
char * arr[3] = { s1, s2, s3 };
To begin with, what you have here:
char **arr;
is a pointer to pointer to char.
Secondly, even if you had an array of pointers to char, like so :
char *arr[3];
And then assigning each string literal :
arr[0]="John";
arr[1]="Doe";
arr[2]="Programmer";
would still invoke Undefined behavior, since you are attempting to modify a string literal which is read only.
What you need is, either a 2D array of chars :
char arr[][100] = {"John", "Doe", "Programmer"};
and also change the function signature to :
void invert(char arr[][100], int n)
or you have to dynamically allocate memory and use a function like strcpy(), strdup(), memcpy() etc :
char **arr;
arr = malloc(n * sizeof(char *)); // or sizeof(*arr)
if (arr == NULL) {
fprintf(stderr, "Malloc failed to allocate memory\n");
exit(1);
}
arr[0] = strdup("John"); // good idea to also check if strdup returned null
arr[1] = strdup("Doe");
arr[2] = strdup("Programmer");
invert(arr, n);
for(i=0;i<3;i++)
{
printf("%s ",arr[i]);
}
for (i = 0; i < 3; i++) {
free(arr[i]);
}
free(arr);
How do I return the address of a global char* variable? I have to do this for a project. I have to write the function based on pseudo code which looks like this:
string* get_variable_address();
C doesn't have string so I assume string* will become char**. I've tried many things but I can't get it to work. What I have looks something like this:
#include <stdio.h>
char test[100] = "Get my address";
int main(void) {
char** address = return_variable_address();
printf("The address is: %s\n", *address);
return 0;
}
char** return_variable_address() {
return &test;
}
C doesn't have string so I assume string* will become char**
Probably not. A string in a C is a character array, which you can access through a char*. Therefore you can simplify your program quite a bit to get the desired result:
#include <stdio.h>
char* return_variable_address (void);
char test[100] = "Get my address";
int main(void) {
char* address = return_variable_address();
printf("The content stored at the address: %s\n", address);
return 0;
}
char* return_variable_address (void) {
return test;
}
Please note that all of this is bad practice - avoid global variables.
Keeping your following requirements in mind -
You want to return a char** where one deferencing once gives you the string "Get my address"
You want the string to be mutable.
So you can do
char test[100] = "Get my address";
char *pointer = test;
char** return_variable_address(void) {
return &pointer;
}
int main(void) {
char** address = return_variable_address();
printf("The address is: %s\n", *address);
(*address)[0] = 'F'; //Test for mutability
printf("The address is: %s\n", *address);
return 0;
}
I understand that these requirements are for some security testing and hence are so peculiar.
Demo here: Ideone
It might help you to typedef a definition of string. Then it is easy to see that the address of a string variable s is just &s as for any other address. I expect that string is used a lot through the project and the typedef will also save you from trying to change every string to char*.
To print an address use the format flag %p.
#include <stdio.h>
typedef char string[10]; // string defined as an arrary of 10 chars
string s = "Hello world"; // I've deliberately put a common error in here
string* return_variable_address( void )
{
return &s;
}
int main( void )
{
printf("Address of global var s = %p \n", return_variable_address() );
return 0;
}
This relates to C. I am having some trouble understanding how I can assign strings to char pointers within arrays from a function.
#include <stdio.h>
#include <string.h>
void function(char* array[]);
int main(void)
{
char* array[50];
function(array);
printf("array string 0: %s\n",array[0]);
printf("array string 1: %s\n",array[1]);
}
void function(char* array[])
{
char temp[] = "hello";
array[0] = temp;
array[1] = temp;
return;
}
Ideally, I would like the main printf function to return
array string 0: hello
array string 1: hello
But I'm having trouble understanding arrays of pointers, how these pass to functions and how to manipulate them in the function. If I declare a string like char temp[] = "string" then how do I assign this to one of the main function array[i] pointers? (assuming I have my jargon right)
char temp[] = "hello"; only creates a local, temporary array inside the function. So when the function exists, the array will be destroyed.
But with array[0] = temp; you're making array[0] point to the local array temp.
After the function returns, temp doesn't exist anymore. So accessing array[0] which pointed to temp will cause undefined behavior.
You could simply make temp static, so it also exists outside the function:
static char temp[] = "hello";
Or, you could copy the "hello" string to array[0] and array[1]. For copying C-strings, you normally use strcpy.
char temp[] = "hello";
strcpy(array[0], temp);
strcpy(array[1], temp);
However, before copying you need to make sure array[0] and array[1] point to memory that has enough space to hold all characters of "hello", including the terminating null character. So you have to do something like this before calling strcpy:
array[0] = malloc(6);
array[1] = malloc(6);
(6 is the minimum numbers of characters that can hold "hello".)
how do I assign this to one of the main function array[i] pointers
Arrays cannot be assigned.
A pointer cannot hold an array, it can only refer to an array. For the latter the pointer needs to get an array's address assigned.
Referring 1.
This
char temp[] = "hello";
isn't an assigment, but an initialisation.
This
char temp[];
temp[] = "hello";
would not compile (the 2nd line errors), as an array cannot be assigned.
Referring 2.
This
char* array[50];
defines an array of 50 pointers to char, it could reference 50 char-arrays, that is 50 C-"strings". It cannot hold the C-"strings" themselfs.
Example
Applying what is mentioned above to your code whould lead to for example the following:
#include <stdio.h>
#include <string.h>
void function(char* array[]);
int main(void)
{
char* array[50];
/* Make the 1st two elements point to valid memory. */
array[0] = malloc(42); /* Real code shall test the outcome of malloc()
as it might fail and very well return NULL! */
array[1] = malloc(42);
function(array);
printf("array string 0: %s\n",array[0]);
printf("array string 1: %s\n",array[1]);
return 0;
}
void function(char* array[])
{
char temp[] = "hello";
/* Copy the content of temp into the memory that was allocated to
the array's 1st memebrs in main(). */
strcpy(array[0], temp);
strcpy(array[1], temp);
return;
}
first, you need to allocate the destination.
second, char temp[] = "hello"; in function() is local variable. you cannot use their outside of the function. use strcpy to copy the content.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void function(char* dest)
{
char temp[] = "hello";
strcpy(dest, temp);
return;
}
int main(void)
{
// or just char dest[10] = {0};
char *dest = malloc(10);
function(dest);
printf("dest: %s\n", dest);
}
In you program, you defined char* array[50];, so you need to create memory space for each item:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void function(char* a[])
{
char temp[] = "hello";
strcpy(a[0], temp);
strcpy(a[1], temp);
return;
}
int main(void)
{
char *a[50];
int i = 0;
for (i = 0; i < 50; ++i)
a[i] = malloc(10);
function(a);
printf("a[0]: %s\n", a[0]);
printf("a[1]: %s\n", a[1]);
}
I'm new in c programming and I want to pass array from library.
I have function in library c file that creates char array. How to use this array in main function. This is short code of something I tried:
libfile.c
char *myArray;
void PopulateArray()
{
// Getting data from serial port in char buffer[100]
myArray = buffer;
}
libfile.h
exter char *myArray;
void PopulateArray();
program.c
int main()
{
// in fore loop
printf("%s\n" , myArray[i]);
}
This is just one of combinations that I have tried but nothing works.
How to do this?
To pass an array from a library function to the surrounding code, you can use the return value of a function or use a pointer-to-pointer argument.
See the following example code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* createSourceCopy() {
const char *source = "Example Text";
// We got some text in variable source;
const size_t sourceSize = strlen(source);
char *result = (char*)malloc(sizeof(char)*(sourceSize+1));
strncpy(result, source, sourceSize);
return result;
}
A user of your library could use the function like this:
main() {
char *result = createSourceCopy();
// Do something with result.
// After the use, destroy the array
delete[] result;
return 0;
}
Another way how to pass an array is this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
bool copySourceText( char **outText ) {
const char *source = "Example Text";
// We get some text in variable source;
const size_t sourceSize = strlen(source);
*outText = new char[sourceSize];
strncpy(*outText, source, sourceSize);
return true; // success
}
This second variant has the benefit that the return value can be used as status. The function could return true on success, or false if there was an error.
This second version can be used like this.
int main() {
char *result;
if (copySourceText(&result)) {
// Do something with result.
// After the use, destroy the array
free(result);
result = NULL;
} else {
// Error handling
}
return 0;
}
It's not clear exactly what's going wrong in the code you posted (it would help to see more code), but assuming your problem isn't a compilation error, one of these lines might be wrong:
char *myArray;
printf("%s\n" , myArray[i]);
char *myArray declares a pointer to char (which would be appropriate for a single string).
The printf line dereferences myArray (producing a char, i.e. one character). You're passing down a char, but the %s format expects a pointer-to-char.
If you want to print the string character-by-character, you could use %c:
for (i = 0; i < length; i++) {
printf("%c\n", myArray[i]); /* or %x or %d if you want */
}
Otherwise, if myArray is one string and is null-terminated (see Why is a null terminator necessary?), then you could do:
printf("%s\n" , myArray); /* [i] removed, no for loop necessary */
I have an assignment to make a dictionary.
It will contain an x amount of words and their definitions (input by user).
Instructions say that the dictionary should be of type char*** (2D array of pointers=arrays=strings), but I've got absolutely no idea of how to dynamically allocate the size of the array. it should have 2 lines, 1 for words and another 1 for their definitions, and the number of columns is decided by how many words are in the dictionary. While looking for help online i came up with this:
char** AllocateArray(int line, int column)
{
char** pArray=(char**)malloc(line*sizeof(char*));
int i;
for(i=0;i<2;i++)
pArray[i]=(char*)malloc(column*sizeof(char));
return pArray;
}
What changes should i make in the code for it to work with my char*** ?
Using Visual studio 2012
Edit:
I have a problem with this right now:
void inputString(char* p1)
{
char buffer[80];
printf("\nEnter a word:");
scanf("%s",buffer);
p1=(char*)malloc(strlen(buffer)+1);
if(p1!=NULL)
{
strcpy(p1,buffer);
free(buffer);
}
}
it crashes right after i input a word. the char* that the function receives is dictionary[i][j]. –
Don't free() anything allocated on the stack (i.e. buffer).
Also, your function inputString() will not tell its client what memory it had allocated, since p1 is local to it.
Here is an example.
char*** dictionary;
int i = 0;
int j = 0;
int lines = 10;
dictionary = (char***)malloc(sizeof(char**)*lines);
for(i=0;i<lines;i++)
{
dictionary[i] = (char**)malloc(sizeof(char*)*4);
for(j=0;j<4;j++)
dictionary[i][j] = (char*)malloc(sizeof(char)*25);
}
You have to modify the malloc's parameters in order to adapt to your problem/ or modify them when you need more memory for your strings.
Also it might be a good idea to try and free memory when you do not need it
Don't forget to malloc like this...
dictionary[i][j] = (char*)malloc(sizeof(char)*strlen(word_to_insert)+1);
...because each word end with a supplementary byte filled with 0 "null terminate string".
a sample
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char ***dictionary;
const char *words[] = { "ASEAN", "United Nations", "OPEC" };
size_t howManyWords = sizeof(words)/sizeof(*words);
int i;
dictionary = malloc(howManyWords*sizeof(char**));
printf("Please enter the definition of this word\n");
for(i = 0; i < howManyWords; ++i){
char buff[80];
char **keyValue;
printf("%s : ", words[i]);
fgets(buff, sizeof(buff), stdin);
keyValue = malloc(2*sizeof(char*));
keyValue[0] = (char*)words[i];
keyValue[1] = malloc(strlen(buff)+1);
strcpy(keyValue[1], buff);
dictionary[i] = keyValue;
}
//print
for(i=0;i<howManyWords;++i){
printf("%s : %s", dictionary[i][0], dictionary[i][1]);
}
//release
for(i=0;i<howManyWords;++i){
free(dictionary[i][1]);
free(dictionary[i]);
}
free(dictionary);
return 0;
}