Rectangle 27 175

Q: What is the difference between these initializations?char a[] = "string literal";char *p = "string literal"; My program crashes if I try to assign a new value to p[i].

A: A string literal (the formal term for a double-quoted string in C source) can be used in two slightly different ways:

  • As the initializer for an array of char, as in the declaration of char a[] , it specifies the initial values of the characters in that array (and, if necessary, its size).
  • Anywhere else, it turns into an unnamed, static array of characters, and this unnamed array may be stored in read-only memory, and which therefore cannot necessarily be modified. In an expression context, the array is converted at once to a pointer, as usual (see section 6), so the second declaration initializes p to point to the unnamed array's first element.

Some compilers have a switch controlling whether string literals are writable or not (for compiling old code), and some may have options to cause string literals to be formally treated as arrays of const char (for better error catching).

K&R section 5.5... Silly me, should have opened the book before asking stupid questions!

Couple of other points: (1) the segfault happens as described, but its occurrence is a function of the run environment; if the same code was in an embedded system, the write may have no effect, or it may actually change the s to a z. (2) Because string literals are non-writable, the compiler can save space by putting two instances of "string" in the same place; or, if somewhere else in the code you have "another string", then one chunk of memory could support both literals. Clearly, if code were then allowed to change those bytes, strange and difficult bugs could occur.

@greggo: Good point. There is also a way to do this on systems with MMU by using mprotect to wave read-only protection (see here).

So char *p="blah" actually creates a temporary array ?weird.

And after 2 years of writing in C++...TIL

c - Why do I get a segmentation fault when writing to a string initial...

c segmentation-fault c-strings
Rectangle 27 6

There should be a way to use the full c:\program files path directly. Often, it involves encapulating the string in quotes. For instance, on the windows command line;

c:\program files\Internet Explorer\iexplore.exe

will not start Internet Explorer, but

"c:\program files\Internet Explorer\iexplore.exe"

windows - How do I specify C:\Program Files without a space in it for ...

windows
Rectangle 27 65

You can use squish method. It removes white space on both ends of the string and groups multiple white space to single space.

" a  b  c ".squish
"a b c"

Note that link-only answers are discouraged, SO answers should be the end-point of a search for a solution (vs. yet another stopover of references, which tend to get stale over time). Please consider adding a stand-alone synopsis here, keeping the link as a reference.

I think this answer was enough explained and the fact that link was reference since the answer itself was clear explained. This function was good, thanks

this works only in ruby on rails

This is from ActiveSupport. You don't need all of Rails to use it, but you do need at least ActiveSupport and a require 'active_support/core_ext/string/filters'

string - Ruby function to remove all white spaces? - Stack Overflow

ruby string
Rectangle 27 65

You can use squish method. It removes white space on both ends of the string and groups multiple white space to single space.

" a  b  c ".squish
"a b c"

Note that link-only answers are discouraged, SO answers should be the end-point of a search for a solution (vs. yet another stopover of references, which tend to get stale over time). Please consider adding a stand-alone synopsis here, keeping the link as a reference.

I think this answer was enough explained and the fact that link was reference since the answer itself was clear explained. This function was good, thanks

this works only in ruby on rails

This is from ActiveSupport. You don't need all of Rails to use it, but you do need at least ActiveSupport and a require 'active_support/core_ext/string/filters'

string - Ruby function to remove all white spaces? - Stack Overflow

ruby string
Rectangle 27 10

This removes the substring C:\Program Files (x86)\Git\bin; from the PATH string and re-assigns:

set PATH=%PATH:C:\Program Files (x86)\Git\bin;=%

You might use this to see the change:

echo %PATH:C:\Program Files (x86)\Git\bin;=% | tr ; \n

Note: be exact on the substring. It's case-sensitive and slash-sensitive.

If you need to make it a persistent change use setx instead of set and open another console for changes to take effect.

windows - Remove unwanted path name from %path% variable via batch - S...

windows batch-file path
Rectangle 27 10

The guarantee is that you get all the characters in the string by incrementing and dereferencing the pointer str, i.e. your string is stored contiguously in memory when the program is running.

And that guarantee is only made if you actually do that (or rather that the compiler cannot prove, up to undefined behavior, you didn't do it), by the as-if rule. What happens when (say) an external program examines the memory of your executable is not defined by the C++ standard.

Does the C++ standard guarantee that string literals are stored in the...

c++ standards
Rectangle 27 324

The system method calls a system program. You have to provide the command as a string argument to this method. For example:

The invoked program will use the current STDIN, STDOUT and STDERR objects of your Ruby program. In fact, the actual return value is either true, false or nil. In the example the date was printed through the IO object of STDIN. The method will return true if the process exited with a zero status, false if the process exited with a non-zero status and nil if the execution failed.

Another side effect is that the global variable $? is set to a Process::Status object. This object will contain information about the call itself, including the process identifier (PID) of the invoked process and the exit status.

>> system("date")
Wed Sep 4 22:11:02 CEST 2013
=> true
>> $?
=> #<Process::Status: pid 15470 exit 0>

Backticks (``) call a system program and return its output. As opposed to the first approach, the command is not provided through a string, but by putting it inside a backticks pair.

>> `date`
=> Wed Sep 4 22:22:51 CEST 2013

The global variable $? is set through the backticks, too. With backticks you can also make use string interpolation.

Using %x is an alternative to the backticks style. It will return the output, too. Like its relatives %w and %q (among others), any delimiter will suffice as long as bracket-style delimiters match. This means %x(date), %x{date} and %x-date- are all synonyms. Like backticks %x can make use of string interpolation.

By using Kernel#exec the current process (your Ruby script) is replaced with the process invoked through exec. The method can take a string as argument. In this case the string will be subject to shell expansion. When using more than one argument, then the first one is used to execute a program and the following are provided as arguments to the program to be invoked.

Sometimes the required information is written to standard input or standard error and you need to get control over those as well. Here Open3.popen3 comes in handy:

require 'open3'

Open3.popen3("curl http://example.com") do |stdin, stdout, stderr, thread|
   pid = thread.pid
   puts stdout.read.chomp
end
STDIN
STDOUT
STDERR
Open3.popen3

Ruby, Difference between exec, system and %x() or Backticks - Stack Ov...

ruby exec
Rectangle 27 324

The system method calls a system program. You have to provide the command as a string argument to this method. For example:

The invoked program will use the current STDIN, STDOUT and STDERR objects of your Ruby program. In fact, the actual return value is either true, false or nil. In the example the date was printed through the IO object of STDIN. The method will return true if the process exited with a zero status, false if the process exited with a non-zero status and nil if the execution failed.

Another side effect is that the global variable $? is set to a Process::Status object. This object will contain information about the call itself, including the process identifier (PID) of the invoked process and the exit status.

>> system("date")
Wed Sep 4 22:11:02 CEST 2013
=> true
>> $?
=> #<Process::Status: pid 15470 exit 0>

Backticks (``) call a system program and return its output. As opposed to the first approach, the command is not provided through a string, but by putting it inside a backticks pair.

>> `date`
=> Wed Sep 4 22:22:51 CEST 2013

The global variable $? is set through the backticks, too. With backticks you can also make use string interpolation.

Using %x is an alternative to the backticks style. It will return the output, too. Like its relatives %w and %q (among others), any delimiter will suffice as long as bracket-style delimiters match. This means %x(date), %x{date} and %x-date- are all synonyms. Like backticks %x can make use of string interpolation.

By using Kernel#exec the current process (your Ruby script) is replaced with the process invoked through exec. The method can take a string as argument. In this case the string will be subject to shell expansion. When using more than one argument, then the first one is used to execute a program and the following are provided as arguments to the program to be invoked.

Sometimes the required information is written to standard input or standard error and you need to get control over those as well. Here Open3.popen3 comes in handy:

require 'open3'

Open3.popen3("curl http://example.com") do |stdin, stdout, stderr, thread|
   pid = thread.pid
   puts stdout.read.chomp
end
STDIN
STDOUT
STDERR
Open3.popen3

Ruby, Difference between exec, system and %x() or Backticks - Stack Ov...

ruby exec
Rectangle 27 4

Python have two types of quotes, " and ' and they are completely equal. So easiest way to get quotes in a string is to say '"C:\Program Files\MPlayer-1.0rc2\mencoder.exe"'.

Using the raw prefix (ie r'"C:\Program Files\MPlayer-1.0rc2\mencoder.exe"') is a good idea, but that is not the error here, as none of the backslashes are followed by a letter that is an escape code. So your original string would not change at all by having an r in front of it.

windows - Using Python to call Mencoder with some arguments - Stack Ov...

python windows mencoder
Rectangle 27 4

Your C++ code is broken. You are returning a pointer to a local variable. It no longer exists after the function returns. This tends to work by accident in a C++ program but is strong Undefined Behavior. It cannot possibly work in an interop scenario, the pinvoke marshaler's use of the stack will overwrite the string.

A declaration that could work:

void function (const char* str, char* output, size_t outputLength)

Use a StringBuilder in the [DllImport] declaration for the output argument and pass an initialized one with sufficient Capacity.

std::string
char*

You already did in your original snippet. But you have to copy the string to output. Use strcpy_s().

c++ - returning c string to a C# program - Stack Overflow

c# c++ string dll export
Rectangle 27 2

You can create a script file on-the-fly in the C program that you will call it from. Note you must handle the characters " and \ and % specially when part of a string literal, by using \" and \\ and %% respectively.

#include <stdio.h>
#include <stdlib.h>

void fatal(char *msg) {
    printf("%s\n", msg);
    exit (1);
    }

void makebat(FILE *fp, char *dirname) {
    fprintf (fp, "@echo off\n");
    fprintf (fp, "\n");
    fprintf (fp, "set \"%s=C:\\Users\\asus\\Desktop\"\n", dirname);
    fprintf (fp, "\n");
    fprintf (fp, "echo:List only files:\n");
    fprintf (fp, "for %%%%a in (\"%%%s%%\\*\") do echo %%%%~fa\n", dirname);
    fprintf (fp, "\n");
    fprintf (fp, "echo:List only directories:\n");
    fprintf (fp, "for /d %%%%a in (\"%%%s%%\\*\") do echo %%%%~fa\n", dirname);
    fprintf (fp, "\n");
    fprintf (fp, "echo:List directories and files in one command:\n");
    fprintf (fp, "for /f \"usebackq tokens=*\" %%%%a in (`dir /b \"%%%s%%\\*\"`) do echo %%%s%%\\%%%%~a\n", dirname, dirname);
    fprintf (fp, "\n");
    fprintf (fp, "pause\n");
}

int main(int argc, char *argv[]) {
    FILE *fp;
    char *fname = "MyScript.bat";
    if ((fp = fopen(fname, "wt")) == NULL)
        fatal("Cannot open script file");

    makebat(fp, "MyDirectory");

    if (fclose (fp))
        fatal("Cannot close script file");
    //system(fname);
    return(0);
}
@echo off

set "MyDirectory=C:\Users\asus\Desktop"

echo:List only files:
for %%a in ("%MyDirectory%\*") do echo %%~fa

echo:List only directories:
for /d %%a in ("%MyDirectory%\*") do echo %%~fa

echo:List directories and files in one command:
for /f "usebackq tokens=*" %%a in (`dir /b "%MyDirectory%\*"`) do echo %MyDirectory%\%%~a

pause

ok thank you but i want to be able to change yourDir too , do you have a solution for that

@satrter see updated answer, the function takes an argument that is used to create the script file.

how to run and modify a cmd script or file in c - Stack Overflow

c cmd
Rectangle 27 4

String a="string with                multi spaces ";
//or this 
String b= a.replaceAll("\\s+"," ");
String c= a.replace("    "," ").replace("   "," ").replace("  "," ").replace("   "," ").replace("  "," ");

//it work fine with any spaces *don't forget space in sting b

Removing whitespace from strings in Java - Stack Overflow

java whitespace
Rectangle 27 4

String a="string with                multi spaces ";
//or this 
String b= a.replaceAll("\\s+"," ");
String c= a.replace("    "," ").replace("   "," ").replace("  "," ").replace("   "," ").replace("  "," ");

//it work fine with any spaces *don't forget space in sting b

Removing whitespace from strings in Java - Stack Overflow

java whitespace
Rectangle 27 4

String a="string with                multi spaces ";
//or this 
String b= a.replaceAll("\\s+"," ");
String c= a.replace("    "," ").replace("   "," ").replace("  "," ").replace("   "," ").replace("  "," ");

//it work fine with any spaces *don't forget space in sting b

Removing whitespace from strings in Java - Stack Overflow

java whitespace
Rectangle 27 34

I want to remove the "(", ")", and "-" characters from the string.

You can use the std::remove_if() algorithm to remove only the characters you specify:

The std::remove_if() algorithm requires something called a predicate, which can be a function pointer like the snippet above.

You can also pass a function object (an object that overloads the function call () operator). This allows us to create an even more general solution:

#include <iostream>
#include <algorithm>
#include <string>

class IsChars
{
public:
    IsChars(const char* charsToRemove) : chars(charsToRemove) {};

    bool operator()(char c)
    {
        for(const char* testChar = chars; *testChar != 0; ++testChar)
        {
            if(*testChar == c) { return true; }
        }
        return false;
    }

private:
    const char* chars;
};

int main()
{
    std::string str("(555) 555-5555");
    str.erase(std::remove_if(str.begin(), str.end(), IsChars("()- ")), str.end());
    std::cout << str << std::endl; // Expected output: 5555555555
}

You can specify what characters to remove with the "()- " string. In the example above I added a space so that spaces are removed as well as parentheses and dashes.

ispunct(int c)

Excellent implementation. This method worked flawlessly and has a lot of room for further dynamics. Thank you for the response. MSalters, I will also look up the ispunct(int c) function and report back on my workings.

How to remove certain characters from a string in C++? - Stack Overflo...

c++ string character
Rectangle 27 2

scanf() has problems, in that if a user is expected to type an integer, and types a string instead, often the program bombs. This can be overcome by reading all input as a string (use getchar()), and then converting the string to the correct data type.

/* example one, to read a word at a time */
#include <stdio.h>
#include <ctype.h>
#define MAXBUFFERSIZE   80

void cleartoendofline( void );  /* ANSI function prototype */

void cleartoendofline( void )
{
    char ch;
    ch = getchar();
    while( ch != '\n' )
        ch = getchar();
}

main()
{
    char    ch;                     /* handles user input */
    char    buffer[MAXBUFFERSIZE];  /* sufficient to handle one line */
    int     char_count;             /* number of characters read for this line */
    int     exit_flag = 0;
    int     valid_choice;

    while( exit_flag  == 0 ) {
        printf("Enter a line of text (<80 chars)\n");
        ch = getchar();
        char_count = 0;
        while( (ch != '\n')  &&  (char_count < MAXBUFFERSIZE)) {
            buffer[char_count++] = ch;
            ch = getchar();
        }
        buffer[char_count] = 0x00;      /* null terminate buffer */
        printf("\nThe line you entered was:\n");
        printf("%s\n", buffer);

        valid_choice = 0;
        while( valid_choice == 0 ) {
            printf("Continue (Y/N)?\n");
            scanf(" %c", &ch );
            ch = toupper( ch );
            if((ch == 'Y') || (ch == 'N') )
                valid_choice = 1;
            else
                printf("\007Error: Invalid choice\n");
            cleartoendofline();
        }
        if( ch == 'N' ) exit_flag = 1;
    }
}

c - Using scanf to accept user input - Stack Overflow

c
Rectangle 27 3

In C++, the program does not have any idea what it's functions are called; That is to say it isn't possible to, (when given a function name as a string) link it back to the original function.

However if you make this connection manually, this can be achieved.

#include <iostream>//for cout
#include <string.h>//for strcmp

using namespace std;

int main(int argc,char **argv){

    if(argc<3){
        cout << "not enough parameters\n";
        return 0;
    }

    if(strcmp(argv[1],"fuction1") == 0){//strcmp() returns 0 if the two strings match
        //call function1 and do something with argv[2]
    }else if(strcmp(argv[1],"function2") == 0){
        //call function2 and do something with argv[2]
    }

    return 0;
}

Although you would still have to decide on whether to treat argv[2] as a plain "string" or as a filename.

@David Sykes this is true. I've been doing a lot of C lately, so I didn't even notice. Thanks and edited.

exe - Example program with some simple functions in C++ - Stack Overfl...

c++ exe
Rectangle 27 3

In C++, the program does not have any idea what it's functions are called; That is to say it isn't possible to, (when given a function name as a string) link it back to the original function.

However if you make this connection manually, this can be achieved.

#include <iostream>//for cout
#include <string.h>//for strcmp

using namespace std;

int main(int argc,char **argv){

    if(argc<3){
        cout << "not enough parameters\n";
        return 0;
    }

    if(strcmp(argv[1],"fuction1") == 0){//strcmp() returns 0 if the two strings match
        //call function1 and do something with argv[2]
    }else if(strcmp(argv[1],"function2") == 0){
        //call function2 and do something with argv[2]
    }

    return 0;
}

Although you would still have to decide on whether to treat argv[2] as a plain "string" or as a filename.

@David Sykes this is true. I've been doing a lot of C lately, so I didn't even notice. Thanks and edited.

exe - Example program with some simple functions in C++ - Stack Overfl...

c++ exe
Rectangle 27 1

A literal string in a C program is considered to be read-only and the compiler/linker/loader may arrange for the memory of that string to be in memory that is protected against writing.

Depending on your compiler and OS, the following may trigger a runtime error:

char *a = "test";
a[0] = 'T';

Of course, if you don't actually try to change the string data, then doing this is not dangerous per se. However, it's useful to get the compiler to assist you in ensuring this by declaring the pointer const:

const char *a = "test";

With this declaration, an attempt to a[0] = 'T' would be a compile error and would therefore be detected much sooner than runtime.

Initializing a char pointer in C. Why considered dangerous? - Stack Ov...

c pointers initialization char
Rectangle 27 1

A literal string in a C program is considered to be read-only and the compiler/linker/loader may arrange for the memory of that string to be in memory that is protected against writing.

Depending on your compiler and OS, the following may trigger a runtime error:

char *a = "test";
a[0] = 'T';

Of course, if you don't actually try to change the string data, then doing this is not dangerous per se. However, it's useful to get the compiler to assist you in ensuring this by declaring the pointer const:

const char *a = "test";

With this declaration, an attempt to a[0] = 'T' would be a compile error and would therefore be detected much sooner than runtime.

Initializing a char pointer in C. Why considered dangerous? - Stack Ov...

c pointers initialization char